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 Q
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.
Also, NoResultException will mark the transaction rolledback in weblogic 10.3.2.
See this article: NoResultException marks transaction rollback
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.
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.