【问题标题】:How to count the results from a Custom Entity using JPA CriteriaQuery如何使用 JPA CriteriaQuery 计算自定义实体的结果
【发布时间】:2016-01-01 07:47:54
【问题描述】:

我正在使用 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); 

下面是我要选择的主线。

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.

如何获得计数?

【问题讨论】:

  • 添加有关实体类及其关系的更多详细信息。给我们讲讲CandidateReport的课程:它的目的是什么?是否有代表它的数据库表?既然cq中没有where子句,那么使用CriteriaQuery#getRestriction()的目的是什么?
  • 当问题说您只需要计数查询时,为什么要显示 2 个查询?

标签: jpa criteria-api jpa-2.1


【解决方案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

【讨论】:

  • 我自己试了 1 个小时,但条件查询太复杂了 :D 这在 5 分钟内解决了我的问题。谢谢。
猜你喜欢
  • 2011-02-22
  • 2019-08-07
  • 1970-01-01
  • 2015-05-15
  • 2012-02-21
  • 2011-04-29
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多