Jeff
Jeff

Reputation:

Why in JPA EntityManager queries throw NoResultException but find does not?

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.

Upvotes: 17

Views: 21444

Answers (4)

Thorsten
Thorsten

Reputation: 291

Queries can be used to retrieve almost anything including the value of a single column in a single row.

If getSingleResult() would return null, you could not tell whether the query did not match any row or whether the query matched a row but the selected column contains null as its value.

Upvotes: 29

smallufo
smallufo

Reputation: 11796

I think it eliminates this null check :

Object o = q.getSingleResult();
if (o != null)
  return (MyObj) o;
return o;

By introducing a RuntimeException (NoResultException) , programmers can safely cast q.getSingleResult() to MyObj , and leave the exception to the caller.

As to q.getResultList() , it will always return a list , null-check is not necessary.

But I still feel this non-intuitive.

Upvotes: -1

Mike
Mike

Reputation: 121

Also, NoResultException will mark the transaction rolledback in weblogic 10.3.2.

See this article: NoResultException marks transaction rollback

Upvotes: 2

Shervin Asgari
Shervin Asgari

Reputation: 24499

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.

Upvotes: 9

Related Questions