简体   繁体   English

在JPA Criteria API查询中使用countDistinct的示例

[英]Example using countDistinct in a JPA Criteria API query

I'm having trouble figuring out how to represent the following JPQL query: 我无法弄清楚如何表示以下JPQL查询:

SELECT count(e) FROM Foo e

using Criteria API. 使用Criteria API。 What I'm trying is: 我正在尝试的是:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Foo> c = cb.createQuery(Foo.class);
Root<Foo> f = c.from(Foo.class);
c.select(cb.count(f));

but this is not working. 但这不起作用。 I also tried: 我也尝试过:

c.select(cb.count(f.get("id"));

This is for JPA2, Eclipselink. 这适用于JPA2,Eclipselink。

try this, this is working with hibernate 3.5.1: 试试这个,这与hibernate 3.5.1一起使用:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> c = cb.createQuery(Long.class);
Root<Foo> f = c.from(Foo.class);
c.select(cb.count(f));
int count = em.createQuery(c).getSingleResult().intValue();

This is a pretty old question but for completness here's a simple addition: 这是一个非常古老的问题,但是对于completness来说这是一个简单的补充:

The title said something about "using countDistinct", so countDistinct should be mentioned here: 标题说了“使用countDistinct”,所以这里应该提到countDistinct:

CriteriaBuilder critBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> critQuery = criteriaBuilder.createQuery(Long.class);
Root<Foo> root = critQuery.from(Foo.class);

critQuery.select(critBuilder.countDistinct(root));
int count = entityManager.createQuery(critQuery).getSingleResult().intValue();

This is important if you don't want to count rows that are double. 如果您不想计算双倍的行,这很重要。 If you want to avoid doule rows in your ResultList, you'd had to use: 如果要避免ResultList中的双行,则必须使用:

CriteriaBuilder critBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> critQuery = criteriaBuilder.createQuery(Long.class);
Root<Foo> root = critQuery.from(Foo.class);

critQuery.select(root).distinct(true);
List<Foo> result = entityManager.createQuery(critQuery).getResultList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM