2015-10-04 56 views
0

我正在使用JPA2.1標準API,其中使用條件生成器構造創建了結果對象。如何使用JPA CriteriaQuery對自定義實體的結果進行計數

請考慮下面的示例代碼片段。

CriteriaBuilder cb;//Assume cb is obtained here 
CriteriaQuery<Report> cq = cb.createQuery(Report.class);// custom selective Class 
Root<Student> root = cq.from(Student.class); 
Join<Student, XTable> join1 = root.join("xtable", JoinType.INNER); 
Join<Student, YTable> join1 = root.join("ytable", JoinType.INNER); 

以下是我選擇的主線。

cq.select(cb.construct(Report.class, 
     root.get("name"), join1.get("address_type"), join2.get("country"))); 

現在,我想要指望這個構造Report

我試過這樣算。

cq.select(cb.count(cb.construct(......))); 
// Failed because count accepts Expression and I tried assigning the cb.construct to Expression which is not working. 

如何獲得計數?

+0

添加對實體類和它們之間的關係更多的細節。告訴我們'CandidateReport'類:它的目的是什麼?有沒有代表它的數據庫表?因爲'cq'中沒有'where'子句,所以使用'CriteriaQuery#getRestriction()'的目的是什麼? – perissf

+0

已更新的問題。 – srk

+0

爲什麼當問題顯示您只需要計數查詢時顯示2個查詢? – perissf

回答

1

我認爲這將是這個樣子:

您的代碼:

CriteriaBuilder cb;//Assume cb is obtained here 
CriteriaQuery<Report> cq = cb.createQuery(Report.class);// custom selective Class 
Root<Student> root = cq.from(Student.class); 
Join<Student, XTable> join1 = root.join("xtable", JoinType.INNER); 
Join<Student, YTable> join1 = root.join("ytable", JoinType.INNER); 
countItemsByCriteria(entityManagerReference, cq, cb); 


private <T> Long countItemsByCriteria(EntityManager em, CriteriaQuery<T> cqEntity, CriteriaBuilder cb) { 
    CriteriaBuilder builder = cb; 
    CriteriaQuery<Long> cqCount = builder.createQuery(Long.class); 
    Root<?> entityRoot = cqCount.from(cqEntity.getResultType()); 
    cqCount.select(builder.count(entityRoot)); 
    cqCount.where(cqEntity.getRestriction()); 
    return em.createQuery(cqCount).getSingleResult(); 
} 

正如這篇文章還介紹:JPA + Hibernate count(*) using CriteriaBuilder - with generatedAlias

相關問題