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?
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 .
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.
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.
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.
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.
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