[英]Hibernate/JPA handling empty result set
我有一個標准構建器,定義為返回Long。 如果結果集為空,則整個應用程序將失敗。 如何處理這個以返回一組數字,例如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;
如果存在空結果集,則Query.getSingleResult()
會拋出一個javax.persistence.NoResultException
,這是一個RuntimeException
。 您可以自由地在try-catch塊中捕獲它並從那里處理它。
要設置最大結果集量,請調用Query.setMaximumResults(int maxResult)
並調用getResultList()
(返回所需實體的List
)。
來自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
考慮捕獲NoResultException的異常並繼續邏輯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.