Close

JPA Criteria API - GroupBy And Having methods of CriteriaQuery

[Updated: Dec 14, 2018, Created: Dec 14, 2018]

The groupBy method of the CriteriaQuery interface is used to define a partitioning of the query results into groups.

The having method of the CriteriaQuery interface can be used to filter over the groups.

package javax.persistence.criteria;
 .....
public interface CriteriaQuery<T> extends AbstractQuery<T> {
 .....
    CriteriaQuery<T> groupBy(Expression<?>... grouping);
    CriteriaQuery<T> groupBy(List<Expression<?>> grouping);
    CriteriaQuery<T> having(Expression<Boolean> restriction);
    CriteriaQuery<T> having(Predicate... restrictions);
 .....
}

Quick Example

  CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
  Root<Employee> employee = query.from(Employee.class);
  query.groupBy(employee.get(Employee_.dept));
  query.multiselect(employee.get(Employee_.dept), criteriaBuilder.max(employee.get(Employee_.salary)));
  query.having(employee.get(Employee_.dept).in("IT", "Admin"));
  TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
  List<Object[]> resultList = typedQuery.getResultList();

Example

Entity

@Entity
public class Employee {
  @Id
  @GeneratedValue
  private long id;
  private String name;
  private String dept;
  private long salary;
    .............
}

Using groupBy() and having()

public class ExampleMain {
  private static EntityManagerFactory entityManagerFactory =
          Persistence.createEntityManagerFactory("example-unit");

  public static void main(String[] args) {
      try {
          persistEmployees();
          findEmployeeCountGroupByDept();
          findEmployeeAvgSalariesGroupByDept();
          findEmployeeCountGroupBySalary();
          findEmployeeMaxSalariesGroupBySelectedDept();
      } finally {
          entityManagerFactory.close();
      }
  }

  private static void findEmployeeCountGroupByDept() {
      System.out.println("-- Employee count group by dept --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
      Root<Employee> employee = query.from(Employee.class);
      query.groupBy(employee.get(Employee_.dept));
      query.multiselect(employee.get(Employee_.dept), criteriaBuilder.count(employee));
      TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
      List<Object[]> resultList = typedQuery.getResultList();
      resultList.forEach(objects ->
              System.out.printf("Dept: %s, Count: %s%n", objects[0], objects[1]));
      entityManager.close();
  }

  private static void findEmployeeAvgSalariesGroupByDept() {
      System.out.println("-- Employee avg salaries group by dept --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
      Root<Employee> employee = query.from(Employee.class);
      query.groupBy(employee.get(Employee_.dept));
      query.multiselect(employee.get(Employee_.dept),
              criteriaBuilder.avg(employee.get(Employee_.salary)));
      TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
      List<Object[]> resultList = typedQuery.getResultList();
      resultList.forEach(objects ->
              System.out.printf("Dept: %s, Avg Salary: %s%n", objects[0], objects[1]));
      entityManager.close();
  }

  private static void findEmployeeCountGroupBySalary() {
      System.out.println("-- Employee count group by salary --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
      Root<Employee> employee = query.from(Employee.class);
      query.groupBy(employee.get(Employee_.salary));
      query.multiselect(employee.get(Employee_.salary), criteriaBuilder.count(employee));
      TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
      List<Object[]> resultList = typedQuery.getResultList();
      resultList.forEach(objects ->
              System.out.printf("Salary: %s, Count: %s%n", objects[0], objects[1]));
      entityManager.close();
  }


  private static void findEmployeeMaxSalariesGroupBySelectedDept() {
      System.out.println("-- Employees max salary group by dept - only in IT and Admin dept --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
      CriteriaQuery<Object[]> query = criteriaBuilder.createQuery(Object[].class);
      Root<Employee> employee = query.from(Employee.class);
      query.groupBy(employee.get(Employee_.dept));
      query.multiselect(employee.get(Employee_.dept),
              criteriaBuilder.max(employee.get(Employee_.salary)));
      query.having(employee.get(Employee_.dept).in("IT", "Admin"));
      TypedQuery<Object[]> typedQuery = entityManager.createQuery(query);
      List<Object[]> resultList = typedQuery.getResultList();
      resultList.forEach(objects ->
              System.out.printf("Dept: %s, Max Salary: %s%n", objects[0], objects[1]));
      entityManager.close();
  }

  public static void persistEmployees() {
      Employee employee1 = Employee.create("Diana", "IT", 3000);
      Employee employee2 = Employee.create("Rose", "Admin", 2000);
      Employee employee3 = Employee.create("Denise", "Admin", 4000);
      Employee employee4 = Employee.create("Mike", "IT", 3500);
      Employee employee5 = Employee.create("Linda", "Sales", 2000);
      EntityManager em = entityManagerFactory.createEntityManager();
      em.getTransaction().begin();
      em.persist(employee1);
      em.persist(employee2);
      em.persist(employee3);
      em.persist(employee4);
      em.persist(employee5);
      em.getTransaction().commit();
      em.close();
      System.out.println("-- all employees --");
      System.out.println(employee1);
      System.out.println(employee2);
      System.out.println(employee3);
      System.out.println(employee4);
      System.out.println(employee5);
  }
}
-- all employees --
Employee{id=1, name='Diana', dept='IT', salary=3000}
Employee{id=2, name='Rose', dept='Admin', salary=2000}
Employee{id=3, name='Denise', dept='Admin', salary=4000}
Employee{id=4, name='Mike', dept='IT', salary=3500}
Employee{id=5, name='Linda', dept='Sales', salary=2000}
-- Employee count group by dept --
Dept: IT, Count: 2
Dept: Sales, Count: 1
Dept: Admin, Count: 2
-- Employee avg salaries group by dept --
Dept: IT, Avg Salary: 3250.0
Dept: Sales, Avg Salary: 2000.0
Dept: Admin, Avg Salary: 3000.0
-- Employee count group by salary --
Salary: 2000, Count: 2
Salary: 4000, Count: 1
Salary: 3500, Count: 1
Salary: 3000, Count: 1
-- Employees max salary group by dept - only in IT and Admin dept --
Dept: IT, Max Salary: 3500
Dept: Admin, Max Salary: 4000

Example Project

Dependencies and Technologies Used:

  • hibernate-core 5.3.7.Final: Hibernate's core ORM functionality.
    Implements javax.persistence:javax.persistence-api version 2.2
  • hibernate-jpamodelgen 5.3.7.Final: Annotation Processor to generate JPA 2 static metamodel classes.
  • h2 1.4.197: H2 Database Engine.
  • JDK 1.8
  • Maven 3.5.4

GroupBy And Having methods of CriteriaQuery Select All Download
  • jpa-criteria-api-group-by-and-having
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also