Close

JPA Criteria API - ORDER BY in Criteria Queries

[Updated: Jul 19, 2018, Created: Jul 19, 2018]

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

CriteriaQuery<T> orderBy(Order... o);

The instance of Order arguments can be created by following methods of CriteriaBuilder:

 Order asc(Expression<?> x);
Order desc(Expression<?> x);

Following code snippet applies order by (both asc and desc) to two columns:

  CriteriaBuilder cb = em.getCriteriaBuilder(); 
  CriteriaQuery<Employee> query = cb.createQuery(Employee.class);//create query object
  Root<Employee> employee = query.from(Employee.class);//create object representing 'from' part
  query.select(employee);//create 'select from' part
  query.orderBy(
        cb.asc(employee.get(Employee_.dept)),
        cb.desc(employee.get(Employee_.salary))
   );

Example

Entity

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

Using Criteria API to apply ordering

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

  public static void main(String[] args) {
      try {
          persistEmployees();
          findEmployeeOrderBySalary();
          findEmployeeOrderByDeptAndSalary();
      } finally {
          entityManagerFactory.close();
      }
  }

  public static void persistEmployees() {
      Employee employee1 = Employee.create("Diana", 2000, "IT");
      Employee employee2 = Employee.create("Rose", 3500, "Admin");
      Employee employee3 = Employee.create("Denise", 2500, "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();
      em.close();
  }

  private static void findEmployeeOrderBySalary() {
      System.out.println("-- All employees order by salary --");
      EntityManager em = entityManagerFactory.createEntityManager();
      CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery<Employee> query = cb.createQuery(Employee.class);//query object
      Root<Employee> employee = query.from(Employee.class);//from part
      query.select(employee);//'select from' part
      query.orderBy(cb.desc(employee.get(Employee_.salary)));//order by part
      TypedQuery<Employee> typedQuery = em.createQuery(query);
      typedQuery.getResultList()
                .forEach(System.out::println);
      em.close();
  }

  private static void findEmployeeOrderByDeptAndSalary() {
      System.out.println("-- All employees order by dept and salary --");
      EntityManager em = entityManagerFactory.createEntityManager();
      CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery<Employee> query = cb.createQuery(Employee.class);//query object
      Root<Employee> employee = query.from(Employee.class);//from part
      query.select(employee);//'select from' part
      query.orderBy(
              cb.asc(employee.get(Employee_.dept)),
              cb.desc(employee.get(Employee_.salary))
      );//order by part
      TypedQuery<Employee> typedQuery = em.createQuery(query);
      typedQuery.getResultList()
                .forEach(System.out::println);
      em.close();
  }
}
-- All employees order by salary --
Employee{id=5, name='Linda', salary=4500.0, dept='Sales'}
Employee{id=4, name='Mike', salary=4000.0, dept='IT'}
Employee{id=2, name='Rose', salary=3500.0, dept='Admin'}
Employee{id=3, name='Denise', salary=2500.0, dept='Admin'}
Employee{id=1, name='Diana', salary=2000.0, dept='IT'}
-- All employees order by dept and salary --
Employee{id=2, name='Rose', salary=3500.0, dept='Admin'}
Employee{id=3, name='Denise', salary=2500.0, dept='Admin'}
Employee{id=4, name='Mike', salary=4000.0, dept='IT'}
Employee{id=1, name='Diana', salary=2000.0, dept='IT'}
Employee{id=5, name='Linda', salary=4500.0, dept='Sales'}

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

ORDER BY in Criteria Queries Example Select All Download
  • jpa-criteria-api-order-by
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources
          • META-INF

See Also