Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional<List<T>> for Empty List in Repository Layer Returns Optional.empty . How do I change it to return Optional[[]]

I have a JPA Query like this.

PersonRepository.java

public Optional<List<PersonEntity>> findByStatus(int status);

PersonService.java

System.out.println(“Optional value is ”+findByStatus(1));

The output is Optional value is Optional.empty

Now I changed my query PersonRepository.java

public List<PersonEntity> findByStatus(int status);

PersonService.java

Optional<List<PersonEntity>> optional = Optional.of(findByStatus(1));
System.out.println("Optional value is "+optional);

The output is Optional value is Optional[[]]

In my database, there is no value for status 1 . I want my output as Optional[[]] for the 1st query. How do I achieve this?

Now, I want to achieve this because, whenever an optional.get() throws a NoSuchElementException, I will handle it using my Exception Controller and expose it as 404 to the REST Layer. But, when a List<Object> is fetched, the response is only a empty List, but optional.get() still throws a NoSuchElementException. I want to avoid this. In short, the optional fetch of Single Entity from Repository throws NoSuchElementException if no value is found which is perfect. But for the optional fetch of a list of Entities which is empty is should be returned as Empty and not throw NoSuchElementException as it is not a 404 error. It just means that the list is empty at present.

like image 287
Phenomenal One Avatar asked Dec 06 '22 11:12

Phenomenal One


1 Answers

 public Optional<List<PersonEntity>> findByStatus(int status);

doesn't make sense.

The correct signature is

 List<PersonEntity> findByStatus(int status);

if there is no PersonEntity the list will be empty.

like image 65
Simon Martinelli Avatar answered Mar 23 '23 00:03

Simon Martinelli