javax.persistence.NoResultException: No entity found for query
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..
}
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);