问题描述
在我发布这个问题之前,我已经看过,但是我无法获得我正在寻找的东西。
我知道,对于我写的查询,可能只存在一行或根本不存在。所以,没有理由使用getResultList ....
这是我的代码
String hql = from DrawUnusedBalance where unusedBalanceDate =:today;
查询查询= em.createQuery(hql);
query.setParameter(today,new LocalDate());
DrawUnusedBalance drawUnusedBalance =
(DrawUnusedBalance)query.getSingleResult(); //我们每天只能有一个
//单个数据
//`系统。 out.println(drawUnusedBalance.toString());`
问题是,如果没有行它会显示一个例外,如果没有,它可以正常工作。我知道这个问题,但我也在寻找最好的解决方案。
我想要的是,如果DB中没有行,我想获得一个空对象(而不是获取异常),所以我将插入一个新的数据。 ..如果它不是null ..我只是想更新它...
有一种方法来处理这个我认为是不正确的方式做它..它是..我会尝试catch块...如果它抛出一个异常我可以写入插入新的数据到数据块中的catch块...但我相信会有一个更好的方式...谢谢你的时间。
是的。您需要使用 try / catch
块,但不需要捕获异常
。 根据,它将抛出 NoResultException
如果没有结果,并且由你决定如何处理它。
DrawUnusedBalance drawUnusedBalance = null;
pre>
try {
drawUnusedBalance =(DrawUnusedBalance)query.getSingleResult()
catch(NoResultException nre){
//忽略这一点,因为根据你的逻辑,这可以!
}
if(drawUnusedBalance == null){
//你的逻辑..
}
Before I posted this question, I already looked this , but I couldn't get what I was looking for.
I know that for the query I wrote there may exist only one row or not at all. So, there is not reason for me to use getResultList .... Here is my code
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 shows 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 ...
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 ... Thank you for your time.
解决方案Yes. You need to use the
try/catch
block, but no need to catch theException
. As per the API it will throwNoResultException
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:找不到用于查询的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!