Search code examples
javajpa-2.0java-ee-6criteria-api

Proper use of aggregate statements in JPA Criteria API


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


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();