如何使用 JPA CriteriaQuery 计算自定义实体的结果

How to count the results from a Custom Entity using JPA CriteriaQuery

我正在使用 JPA2.1 标准 API,其中我使用标准构建器构造创建了一个结果对象。

考虑下面的示例代码。

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); 

下面是我要 select.

的主线
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.

如何获取计数?

我认为它看起来像这样:

您的代码:

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();
}

正如本 post 中所述:JPA + Hibernate count(*) using CriteriaBuilder - with generatedAlias