Akhil Prajapati
Akhil Prajapati

Reputation: 1281

Spring Data JPA findById() method returning null instead of Empty Optional

I have a method that is making use of Spring Data JPA's findById() method is supposed to return an Optional. However, in case the entity is not found by the specified id, it is returning null instead of an Empty Optional.

 public TicketEntity findTicket(String ticket) throws EntityNotFoundException {

    Optional<TicketEntity> op = ticketEntityRepository.findById(ticket);

    TicketEntity ticketEntity = op.orElseThrow(() -> new EntityNotFoundException("ticket with the id " + ticket + " not found in the system"));

    return ticketEntity;
}

While debugging, I found that the value of op is null. This is the piece of code that is failing. I am using Spring Data JPA 2.0.8.RELEASE. Please help

Upvotes: 4

Views: 18911

Answers (3)

M. Deinum
M. Deinum

Reputation: 124441

In a comment you state that this is in a test with mocked dependencies. The mocking takes Spring Data JPA out of the picture completely as it now is just a proxy implemented by a mock from Mockito.

The default behavior for a mock is to return null.

By default, for all methods that return a value, a mock will return either null, a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.

As you are running with a mock you will need to instruct it to return an Optional.empty() else you will get null.

NOTE: You might want to create an improvement request for Mockito to default return Optional.empty in the case of an Optional return type.

Upvotes: 4

mahsum
mahsum

Reputation: 350

What is the implementation of your Repository Class? The following repository and test case works for me.

@RunWith(SpringRunner.class)
@SpringBootTest
public class PersonRepoTest {

    @Autowired
    private PersonRepository personRepository;

    @Test
    public void testFindById(){
        Optional<Person> byId = personRepository.findById(1);
        Assert.assertTrue(byId != null);
    }
}

public interface PersonRepository  extends CrudRepository<Person, Integer> {
}

Upvotes: 1

Bhumi Nandan Chettri
Bhumi Nandan Chettri

Reputation: 43

The line of code

Optional op = ticketEntityRepository.findById(ticket);

return list of result set if data exists in the system, otherwise it is obvious that it will return null instead of empty optional. If you need an empty optional list you can twist it as follows

List op = ticketEntityRepository.findById(ticket).orElse(new ArrayList());

Upvotes: -4

Related Questions