views:

2204

answers:

4

And if so, under what circumstances?

Javadoc and JPA spec says nothing.

+5  A: 

If the specs said it could't happen, would you belive them? Given that your code could conceivably run against may different JPA implementations, would you trust every implementer to get it right?

No matter what, I would code defensively and check for null.

Now the big question: should we treat "null" and an empty List as synonymous? This is where the specs should help us, and don't.

My guess is that a null return (if indeed it could happen) would be equivalent to "I didn't understand the query" and empty list would be "yes, understood the query, but there were no records".

You perhaps have a code path (likely an exception) that deals with unparsable queries, I would tend to direct a null return down that path.

djna
+1 you are so right when saying: "would you trust every JPA provider?" NO :)
dfa
Edited to add: Arthur has pointed out that Hibernate's JPA in fact returns null if no records are found. So in fact in this case, we do need to fold together null and empty list. I believe that the thought process we went through above is still valid.It is even conceivable that we should have different treatments of null for different JPA stacks. Welcome to portability fun.
djna
Agreed. There only exists "portability fun" due to the JPA spec not doing what it should do ... specify the precise semantics. Shame it is run by committee with vested interests.
DataNucleus
+2  A: 

Hi,

You are right. JPA specification says nothing about it. But Java Persistence with Hibernate book says:

If the query result is empty, a null is returned

Hibernate JPA implementation (Entity Manager) return null when you call query.getResultList() with no result.

Arthur Ronald F D Garcia
+1  A: 

Contrary to Arthur's post, when I actually ran a query which no entities matched I got an empty list, not null. This is using Hibernate and is what I consider correct behaviour: an empty list is the correct answer when you ask for a collection of entities and there aren't any.

Andrew Simons
A: 

Of course, if you test the result set with Jakarta's CollectionUtils.isNotEmpty, you're covered either way.

Al Scherer