如何使用JPA CriteriaQuery计算自定义实体的结果
我使用的是JPA2.1 criteria API,其中我使用criteria builder构造创建了一个结果对象 考虑下面的代码示例如何使用JPA CriteriaQuery计算自定义实体的结果,jpa,criteria-api,jpa-2.1,Jpa,Criteria Api,Jpa 2.1,我使用的是JPA2.1 criteria API,其中我使用criteria builder构造创建了一个结果对象 考虑下面的代码示例 CriteriaBuilder cb;//Assume cb is obtained here CriteriaQuery<Report> cq = cb.createQuery(Report.class);// custom selective Class Root<Student> root = cq.from(Student.cl
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.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();
}
正如这篇文章中所描述的:我认为它看起来像这样: 您的代码:
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();
}
如本文所述:添加有关实体类及其关系的更多详细信息。告诉我们关于班级候选人报告:它的目的是什么?有代表它的db表吗?既然cq中没有where子句,那么使用CriteriaQuerygetRestriction的目的是什么?当问题说您只需要count查询时,为什么要显示2个查询?添加有关实体类及其关系的更多详细信息。告诉我们关于班级候选人报告:它的目的是什么?有代表它的db表吗?既然cq中没有where子句,那么使用CriteriaQuerygetRestriction的目的是什么?当问题说您只需要count查询时,为什么要显示2个查询?我自己尝试了1个小时,但条件查询太复杂了:D这在5分钟内解决了我的问题。谢谢。我自己试了一个小时,但条件查询太复杂了:D这在5分钟内解决了我的问题。谢谢