views:

683

answers:

1

Can somebody tell me the intrinsic reasons why in the JPA 1.0 EntityManager when retrieving an Object via find, you have to deal with null if not found, but when using the Query interface via createQuery getResultList throws a NoResultException when not found.

Maybe i am missing something but I feel its very inconsistent for a Language, and actually I had to do a lot of redesing because of changing from a simple finder to a more fine grained query using the query interface.

Thanks guys.

A: 

When you do a find, jpa will use the primary key to locate the entity object, often using second level cache and it is typically much faster than createQuery and getSingleResult.

You either get null or the Object back from find. When you do a createQuery and instance of Query object is created. If you do a getResultList it will not throw a NoResultException, only if you do a getSingleResult will it throw that exception. If you do a getResultList and none is found, then null will be returned.

Shervin
Thats correct yes. It is still not very clear to me why the JPA spec folks decided in one case throw a noresultexception and in the other just return null, if its logically very similar operation. That it is an unchecked exception doesn't make it easier ... or turned around: What speaked against returning null from getSingleResult vs. throwing an Exception? In my point of view that would be more consistent: Either throw a NoREsultExcpetion in getSingleResult and find or returning null. but not mix it.