更好的方法是:JPA的getSingleResult或getResultList [英] what is better: getSingleResult, or getResultList JPA
问题描述
我需要从表中检索单个行,并且我对哪种方法更好感兴趣.
一方面,getSingleResult
设计用于检索单个结果,但是会引发异常.此方法是否对与getResultList
和
i need to retrieve single row from table, and i was interested what approach is better.
On the one side getSingleResult
is designed for retrieving single result, but it raises exception. Does this method have benefit in performance related to getResultList
with
query.setFirstResult(0);
query.setMaxResults(1);
推荐答案
getSingleResult
如果存在多行,则抛出NonUniqueResultException
.它旨在在真正存在单个结果时检索单个结果.
getSingleResult
throws NonUniqueResultException
, if there are multiple rows. It is designed to retrieve single result when there is truly a single result.
您的工作方式很好,并且JPA可以正确处理此问题.同时,您无法将它与getSingleResult
进行任何比较,因为它无法正常工作.
The way you did is fine and JPA is designed to handle this properly. At the same time, you cannot compare it against getSingleResult
any way, since it won't work.
但是,根据您正在使用的代码,始终最好对查询进行细化以返回单个结果,如果这就是您想要的全部,那么只需调用getSingleResult
.
However, depend on the code you are working on, it is always better to refine the query to return single result, if that's all what you want - then you can just call getSingleResult
.
这篇关于更好的方法是:JPA的getSingleResult或getResultList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!