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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With