JPA getSingleResult()或null [英] JPA getSingleResult() or null

查看:68
本文介绍了JPA getSingleResult()或null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 insertOrUpdate 方法,该方法在不存在时插入实体,如果有,则更新它。要启用此功能,我必须 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 抛出例外

谢谢

推荐答案

抛出异常是 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆