简体   繁体   English

Hibernate / JPA处理空结果集

[英]Hibernate/JPA handling empty result set

I have a criteria builder which is defined as returning a Long. 我有一个标准构建器,定义为返回Long。 If the result set is empty, the whole application fails. 如果结果集为空,则整个应用程序将失败。 How do I handle this to return a set number, eg 1000? 如何处理这个以返回一组数字,例如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 . 如果存在空结果集,则Query.getSingleResult()会抛出一个javax.persistence.NoResultException ,这是一个RuntimeException You are free to catch it in a try-catch block and handle it from there. 您可以自由地在try-catch块中捕获它并从那里处理它。

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). 要设置最大结果集量,请调用Query.setMaximumResults(int maxResult)并调用getResultList() (返回所需实体的List )。

From JPA API 来自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 考虑捕获NoResultException的异常并继续逻辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM