Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of JPA query when no matches found

I'm using Spring JPA named querys in my repository. My problem is, that I can't find anywhere information what would be returned value for a query that wouldn't match any results. I assume it'll be null for findOne() but I have no idea what would it be for findAllByName() function.

Does anyone know from his/her experience or know a place in documentation?

like image 273
xenteros Avatar asked Jul 20 '16 11:07

xenteros


People also ask

Does Spring JPA return empty list or null?

The normal behavior is indeed returning an empty list if no results are found. If a List<Object> is the return value of the method in the defined interface, the method should never return Null .

What does findById return in JPA?

Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.

What is the use of @query in JPA?

Understanding the @Query Annotation The @Query annotation can only be used to annotate repository interface methods. The call of the annotated methods will trigger the execution of the statement found in it, and their usage is pretty straightforward. The @Query annotation supports both native SQL and JPQL.

Is empty in JPA query?

The IS EMPTY operator is the logical equivalent of IS NULL, but for collections. Queries can use IS EMPTY operator or IS NOT EMPTY to check whether a collection association path resolves to an empty collection or has at least one value.


1 Answers

From my little and personal experience, if you search for an object on your repo, for example by Id or Name the named query method returns an object of type T, but if no results are found from your repo, it will return null.

Methods that can return more than one element, will produce an empty collection List<T>(not null).

Some documentation here: http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords

Appendix D: Repository query return types

Supported query return types Query return types:

T An unique entity. Expects the query method to return one result at most. In case no result is found null is returned. More than one result will trigger an IncorrectResultSizeDataAccessException.

Iterator An Iterator.

Seems like only when return type is of type T is the only one that specify a null is returned if no matches.

like image 137
exoddus Avatar answered Sep 25 '22 18:09

exoddus