javax.persistence.NoResultException:未找到查询的实体 [英] javax.persistence.NoResultException: No entity found for query

查看:25
本文介绍了javax.persistence.NoResultException:未找到查询的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我发布这个问题之前,我已经看过这个,但我找不到我要找的东西.

Before I posted this question, I already looked this, but I couldn't get what I was looking for.

我知道对于我写的查询,可能只存在一行或根本不存在.所以,我没有理由使用 getResultList().

I know that for the query I wrote there may exist only one row or none at all. So, there is not reason for me to use getResultList().

这是我的代码:

String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
Query query=em.createQuery(hql);
query.setParameter("today",new LocalDate());

DrawUnusedBalance drawUnusedBalance= 
    (DrawUnusedBalance)query.getSingleResult();// we can have only a
                                               // single datum per day
//`System.out.println(drawUnusedBalance.toString());`

问题是,如果没有行,则抛出异常,如果没有,则工作正常.我知道问题所在,但我也在寻找最佳解决方案.

The problem is, if there is no row, it throws an exception, and if not it works fine. I know the problem but I am also looking for the best solution.

我想要的是,如果数据库中没有行,我想获得一个空对象(而不是获得异常),所以我将插入一个新数据,如果它不为空,我只想更新它.

What I wanted is, if there is no row in the DB I wanted to get a null object (instead of getting an exception) so I will insert a new data, if it is not null, I just want to update it.

有一种方法可以解决这个问题,我认为这不是正确的方法.它是:我将有一个 try-catch 块,如果它引发异常,我可以写入以将新数据插入到 catch 块上的数据库中.但我相信会有更好的方法.

There is one way to handle this, which I believe is not the right way to do it. It is: I will have a try-catch block and if it throws an exception I can write to insert new data in to the DB on the catch block. But I believe there will be a better way.

推荐答案

是的.您需要使用 try/catch 块,但不需要捕获 Exception.根据 API 它将抛出 NoResultException如果没有结果,则由您决定如何处理.

Yes. You need to use the try/catch block, but no need to catch the Exception. As per the API it will throw NoResultException if there is no result, and its up to you how you want to handle it.

DrawUnusedBalance drawUnusedBalance = null;
try{
drawUnusedBalance = (DrawUnusedBalance)query.getSingleResult()
catch (NoResultException nre){
//Ignore this because as per your logic this is ok!
}

if(drawUnusedBalance == null){
 //Do your logic..
}

这篇关于javax.persistence.NoResultException:未找到查询的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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