Example using countDistinct in a JPA Criteria API query

13,225

Solution 1

try this, this is working with 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();

Solution 2

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:

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:

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();
Share:
13,225
Tim
Author by

Tim

Updated on June 11, 2022

Comments

  • Tim
    Tim almost 2 years

    I'm having trouble figuring out how to represent the following JPQL query:

    SELECT count(e) FROM Foo e
    

    using 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.