Search code examples
hibernatehibernate-mappinghibernate-annotations

Hibernate query output for rows that don't exist


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?


Solution

  • 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;
      }
    }