I have a criteria builder which is defined as returning a Long. If the result set is empty, the whole application fails. How do I handle this to return a set number, eg 1000?
Long yesterday = new Long(0);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> q = cb.createQuery(Long.class);
Root<CustomerHistory> hist = q.from(CustomerHistory.class);
q.multiselect(hist.get("total"));
Date yesterDate = new LocalDate().minusDays(1).toDateTimeAtStartOfDay().toDate();
Predicate w1 = cb.equal(hist.<Date>get("date"), yesterDate);
Predicate w2 = cb.equal(hist.get("customer"), customer);
q.where(w1,w2);
yesterday = em.createQuery(q).getSingleResult();
return yesterday < tot;
If there is an empty resultset, the Query.getSingleResult()
throws a javax.persistence.NoResultException
which is a RuntimeException
. You are free to catch it in a try-catch block and handle it from there.
To set the maximum amount of result set, call the Query.setMaximumResults(int maxResult)
and call the getResultList()
(which returns a List
of the entity desired).
From JPA API
java.lang.Object getSingleResult()
Execute a SELECT query that returns a single untyped result.
Returns:
the result
Throws:
NoResultException - if there is no result
NonUniqueResultException - if more than one result
Consider catch the Exception of NoResultException and continue with the logic
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.