views:

100

answers:

1

What is the rationale behind throwing an exeption in JPA, when something can't be found?
Added: This behaviour was seen in EJB2, and has as far been removed from EJB3 - but... It remains when calling Query#getSingleResult() which throws a NoResultException.

Normally I would not expect it to be an exception that something could not be found. Actually this might me the default situation in some cases, and at leats the expected cases in most other sotuations. It makes me remeber an old saying that you should not use exceptions as part of your business logic, but only as what it is, special cases you don't know how or don't want to deal with.

Does anyone have an idea why it is implemented this way in JPA? What is the drawback on returning null when something could not be found?

+2  A: 

Are you calling getReference(class, primaryKey)? That will throw an exception if the primary key doesn't exist; if you'd like null object returned, use find(class, primaryKey) instead. getReference() allows lazy loading, which find() doesn't, but the side-effect of that is that to allow lazy-loading you need to be referring to a real object, which means that you must pass a valid PK.

Cowan