JPA getSingleResult() 或 null [英] JPA getSingleResult() or null
问题描述
我有一个 insertOrUpdate
方法,它在 Entity
不存在时插入它,如果存在则更新它.要启用此功能,我必须findByIdAndForeignKey
,如果它返回null
,则插入,否则更新.问题是我如何检查它是否存在?所以我尝试了 getSingleResult
.但是如果
I have an insertOrUpdate
method which inserts an Entity
when it doesn't exist or update it if it does. To enable this, I have to findByIdAndForeignKey
, if it returned null
insert if not then update. The problem is how do I check if it exists? So I tried getSingleResult
. But it throws an exception if the
public Profile findByUserNameAndPropertyName(String userName, String propertyName) {
String namedQuery = Profile.class.getSimpleName() + ".findByUserNameAndPropertyName";
Query query = entityManager.createNamedQuery(namedQuery);
query.setParameter("name", userName);
query.setParameter("propName", propertyName);
Object result = query.getSingleResult();
if (result == null) return null;
return (Profile) result;
}
但是getSingleResult
抛出一个Exception
.
谢谢
推荐答案
抛出异常的方法 getSingleResult()
表示无法找到.我个人无法忍受这种 API.它强制进行虚假的异常处理而没有真正的好处.您只需要将代码包装在 try-catch 块中.
Throwing an exception is how getSingleResult()
indicates it can't be found. Personally I can't stand this kind of API. It forces spurious exception handling for no real benefit. You just have to wrap the code in a try-catch block.
或者,您可以查询列表并查看其是否为空.那不会抛出异常.实际上,由于您在技术上没有进行主键查找,因此可能会出现多种结果(即使其中一个、两个或外键或约束的组合在实践中都无法实现),因此这可能是更合适的解决方案.
Alternatively you can query for a list and see if its empty. That doesn't throw an exception. Actually since you're not doing a primary key lookup technically there could be multiple results (even if one, both or the combination of your foreign keys or constraints makes this impossible in practice) so this is probably the more appropriate solution.
这篇关于JPA getSingleResult() 或 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!