Close

JPA Criteria API - Distinct clause in Criteria API

[Updated: Aug 13, 2018, Created: Aug 13, 2018]

In Criteria API distinct clause can be applied by using following method of CriteriaQuery:

 CriteriaQuery<T> distinct(boolean distinct);

Quick example:

    CriteriaQuery<String> query = .......
    Root<Employee> employee = query.from(Employee.class);
    query.select(employee.get(Employee_.name))
         .distinct(true);

Example

Entity

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

Applying distinct clause

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

  public static void main(String[] args) {
      try {
          persistEmployees();
          findDistinctDepts();
          findDistinctSalaries();
          findDistinctDeptAndSalaries();
      } finally {
          entityManagerFactory.close();
      }
  }

  public static void persistEmployees() {
      Employee employee1 = Employee.create("Diana", 2000, "IT");
      Employee employee2 = Employee.create("Rose", 4500, "Admin");
      Employee employee3 = Employee.create("Denise", 2000, "Admin");
      Employee employee4 = Employee.create("Mike", 4000, "IT");
      Employee employee5 = Employee.create("Linda", 4500, "Sales");
      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();
      System.out.println("-- employee persisted --");
      CriteriaQuery<Employee> query = em.getCriteriaBuilder()
                                        .createQuery(Employee.class);
      query.select(query.from(Employee.class));
      em.createQuery(query).getResultList().forEach(System.out::println);
      em.close();
  }

  private static void findDistinctDepts() {
      System.out.println("-- Distinct dept --");
      EntityManager em = entityManagerFactory.createEntityManager();
      CriteriaQuery<String> query = em.getCriteriaBuilder()
                                      .createQuery(String.class);
      Root<Employee> employee = query.from(Employee.class);
      query.select(employee.get(Employee_.dept))
           .distinct(true);
      TypedQuery<String> tq = em.createQuery(query);
      List<String> resultList = tq.getResultList();
      resultList.forEach(System.out::println);
  }

  private static void findDistinctSalaries() {
      System.out.println("-- Distinct salaries order by salary desc --");
      EntityManager em = entityManagerFactory.createEntityManager();
      CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery<Double> query = cb.createQuery(Double.class);
      Root<Employee> employee = query.from(Employee.class);
      query.select(employee.get(Employee_.salary))
           .orderBy(cb.desc(employee.get(Employee_.salary)))
           .distinct(true);
      TypedQuery<Double> tq = em.createQuery(query);
      List<Double> resultList = tq.getResultList();
      resultList.forEach(System.out::println);
  }

  private static void findDistinctDeptAndSalaries() {
      System.out.println("-- Distinct dept and salaries order by dept asc and salary desc --");
      EntityManager em = entityManagerFactory.createEntityManager();
      CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery<Object[]> query = cb.createQuery(Object[].class);
      Root<Employee> employee = query.from(Employee.class);
      query.multiselect(employee.get(Employee_.dept), employee.get(Employee_.salary))
           .orderBy(cb.asc(employee.get(Employee_.dept)), cb.desc(employee.get(Employee_.salary)))
           .distinct(true);
      TypedQuery<Object[]> tq = em.createQuery(query);
      List<Object[]> resultList = tq.getResultList();
      resultList.forEach(arr -> System.out.println(Arrays.toString(arr)));
  }
}
-- employee persisted --
Employee{id=1, name='Diana', salary=2000.0, dept='IT'}
Employee{id=2, name='Rose', salary=4500.0, dept='Admin'}
Employee{id=3, name='Denise', salary=2000.0, dept='Admin'}
Employee{id=4, name='Mike', salary=4000.0, dept='IT'}
Employee{id=5, name='Linda', salary=4500.0, dept='Sales'}
-- Distinct dept --
IT
Sales
Admin
-- Distinct salaries order by salary desc --
4500.0
4000.0
2000.0
-- Distinct dept and salaries order by dept asc and salary desc --
[Admin, 4500.0]
[Admin, 2000.0]
[IT, 4000.0]
[IT, 2000.0]
[Sales, 4500.0]

Example Project

Dependencies and Technologies Used:

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

Distinct clause in Criteria API Select All Download
  • jpa-criteria-api-distinct-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also