30

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?

xenteros
  • 15,586
  • 12
  • 56
  • 91

1 Answers1

39

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.

exoddus
  • 2,230
  • 17
  • 27
  • 3
    damn NP hehe! how many if != null statements will be avoided by better reading / better documentation. – exoddus Jul 20 '16 at 12:25
  • A repository with @RepositoryRestResource incase of an empty list, will return a list with one "dummyObject" ..how could i make it return just an empty list? It returns this:"content": [ { "value": [], "rel": null, "collectionValue": true, "relTargetType": "com.xy.xy.xy.model.Campaign" } ]-------------------but i need just content[] – Daniel Jeney Dec 18 '19 at 08:34