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

核能气质少年 提交于 2019-12-17 19:18:57

问题


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.


回答1:


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.




回答2:


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.




回答3:


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

See this article: NoResultException marks transaction rollback




回答4:


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.



来源:https://stackoverflow.com/questions/1579560/why-in-jpa-entitymanager-queries-throw-noresultexception-but-find-does-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!