我对JPA2比较陌生,它是CriteriaBuilder / CriteriaQuery API:
CriteriaQuery
in the Java EE 6 tutorial
我想对CriteriaQuery的结果进行计数,而不实际检索它们。有没有可能,我没有找到这样的方法,唯一的办法就是这样做:
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<MyEntity> cq = cb
.createQuery(MyEntityclass);
// initialize predicates here
return entityManager.createQuery(cq).getResultList().size();
这不可能是正确的方式。
有解决方案吗?
发布于 2010-05-22 01:58:16
类型为MyEntity
的查询将返回MyEntity
。您想要查询一个Long
。
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(/*your stuff*/);
return entityManager.createQuery(cq).getSingleResult();
显然,您将希望使用在示例中跳过的任何限制和分组等构建表达式。
发布于 2012-05-12 02:51:37
我已经使用cb.createQuery() (不带result类型参数)解决了这个问题:
public class Blah() {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery query = criteriaBuilder.createQuery();
Root<Entity> root;
Predicate whereClause;
EntityManager entityManager;
Class<Entity> domainClass;
... Methods to create where clause ...
public Blah(EntityManager entityManager, Class<Entity> domainClass) {
this.entityManager = entityManager;
this.domainClass = domainClass;
criteriaBuilder = entityManager.getCriteriaBuilder();
query = criteriaBuilder.createQuery();
whereClause = criteriaBuilder.equal(criteriaBuilder.literal(1), 1);
root = query.from(domainClass);
}
public CriteriaQuery<Entity> getQuery() {
query.select(root);
query.where(whereClause);
return query;
}
public CriteriaQuery<Long> getQueryForCount() {
query.select(criteriaBuilder.count(root));
query.where(whereClause);
return query;
}
public List<Entity> list() {
TypedQuery<Entity> q = this.entityManager.createQuery(this.getQuery());
return q.getResultList();
}
public Long count() {
TypedQuery<Long> q = this.entityManager.createQuery(this.getQueryForCount());
return q.getSingleResult();
}
}
希望它能有所帮助:)
发布于 2010-05-22 01:56:46
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
cq.select(cb.count(cq.from(MyEntity.class)));
return em.createQuery(cq).getSingleResult();
https://stackoverflow.com/questions/2883887
复制相似问题