Proper use of aggregate statements in JPA Criteria API

criteria-api, java, java-ee-6, jpa-2.0

Solution

Hope, this should help you:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<Long> countCriteriaQuery = builder.createQuery( Long.class );
countCriteriaQuery.select( builder.countDistinct( countQuery.from( MyClass.class ) ) );

TypedQuery<Long> countQuery = entityManager.createQuery( countCriteriaQuery );
int totalObjectsNumber = countQuery.getSingleResult().longValue();

Problem

I am struggling with the proper use of aggregate statements like `countDistinct`. I have found some examples for aggregate queries but none that is executed start-to-finish using `countDistinct`. I have tried this: ``` final CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder(); final CriteriaQuery<MyClass> query = criteriaBuilder.createQuery(MyClass.class); final Root<MyClass> root = query.from(MyClass.class); final Predicate yearPredicate = criteriaBuilder.equal(root.get("year"), currentYear); query.select(root); query.where(yearPredicate); final Expression<Long> count = criteriaBuilder.countDistinct(root); ``` Here is where I am stuck. Is it correct to run `countDistinct` on the root? How do I get the result? `query.select(count);` and `criteriaBuilder.countDistinct(query)` are both illegal. It would be great if someone could point me in the right direction. Thank you

Original source