Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.persistence.NoResultException: No entity found for query

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 none 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 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.

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.

like image 763
WowBow Avatar asked Nov 15 '11 15:11

WowBow


2 Answers

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..
}
like image 100
ManuPK Avatar answered Oct 09 '22 12:10

ManuPK


When using java 8, you may take advantage of stream API and simplify code to

return (YourEntityClass) entityManager.createQuery()
....
.getResultList()
.stream().findFirst();

That will give you java.util.Optional

If you prefer null instead, all you need is

 ...
.getResultList()
.stream().findFirst().orElse(null);
like image 40
Bartosz Bilicki Avatar answered Oct 09 '22 11:10

Bartosz Bilicki