0

I've a Hibernate query:

StringBuilder sb = new StringBuilder("" +
                "SELECT d.value " +
                "FROM Table d " +
                "WHERE d.date = :date ");

        Query q = em.createQuery(sb.toString())
                .setParameter("date",date);

        BigDecimal result = (BigDecimal) q.getSingleResult();

        if (result == null)
            result = BigDecimal.ZERO;

        return result;

When I pass date that exists in Table it works good, but when I pass Date that doesn't exists it returns an Exception javax.persistence.NoResultException: No entity found for query

I've tried to put @NotFound(action = NotFoundAction.IGNORE) annotation under each filed of Table, but Exception is the same. How can I handle this problem?

2
  • the stringbuilder used in this way is completely useless, you are concatenating string in the stringbuilder constructor.. Commented Sep 3, 2015 at 10:06
  • I know, I'll use it later on when adding some new paarmeters Commented Sep 3, 2015 at 10:07

2 Answers 2

3

single result throws an exception when there is no result, you could either catch that exception and then return null, either q.getResultList(), and then check the list, in this way you could see if there ar duplicates too, case in which single result throws another exception.

from javadoc :

Throws:
    NoResultException - if there is no result
    NonUniqueResultException - if more than one result

handle the exception will be like :

 Query q = em.createQuery(sb.toString())
            .setParameter("date",date);
  try {
     BigDecimal result = (BigDecimal) q.getSingleResult();
     return result;
  } catch (NoResultException e){
     return BigDecimal.ZERO;
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

There is no duplicates, I've two entries in Table. Isn't it possible to handle it in map?
You would like the results in a map ?
I mean there should be some annotations like @NotFound to handle similar situations
there isn't, you just have to handle the exception
1

I don't think there is anything wrong with your query. That's the behavior of Query.getSingleResult() method. As Radu Toader suggested you could use Query.getResultList() or another way to handle this is to wrap it in try catch block.

BigDecimal result = null;
try{
   result = (BigDecimal) q.getSingleResult();
} catch(NoResultException e) {
   //log exception or throw it...
}
return result;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.