java 在 JPA Criteria API 查询中使用 countDistinct 的示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2595065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Example using countDistinct in a JPA Criteria API query
提问by Tim
I'm having trouble figuring out how to represent the following JPQL query:
我无法弄清楚如何表示以下 JPQL 查询:
SELECT count(e) FROM Foo e
using Criteria API. What I'm trying is:
使用标准 API。我正在尝试的是:
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。
回答by Buchi
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();
回答by AlexS
This is a pretty old question but for completness here's a simple addition:
这是一个相当古老的问题,但为了完整起见,这里有一个简单的补充:
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();

