Close

JPA Criteria API - Assigning Aliases to Selection Items

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

Following method of Selection interface can be used to assign an alias to query selection items:

Selection<X> alias(String name);

The assigned alias may then later be used to extract the corresponding item from the query result when the query is executed. This is typically used with Tuple of objects as query result. Following are the two methods of Tuple to extract result value by alias:

Object get(String alias);
X get(String alias, Class<X> type); 

Quick example:

  CriteriaQuery<Tuple> query = criteriaBuilder.createTupleQuery();
  Root<Employee> employee = query.from(Employee.class);
  query.multiselect(employee.get(Employee_.name).alias("employeeName"),
                employee.get(Employee_.dept).alias("dept"));
  TypedQuery<Tuple> typedQuery = entityManager.createQuery(query);
  for (Tuple tuple : typedQuery.getResultList()) {
       String employeeName = tuple.get("employeeName", String.class);
       Object dept = tuple.get("dept");
    ...
   }

Example

Entity

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

Using Selection#alias()

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

  public static void main(String[] args) {
      try {
          persistEmployees();
          findAllEmployeeEntities();
          findEmployeeBySalaries();
      } 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();
      em.close();
  }

  private static void findAllEmployeeEntities() {
      System.out.println("-- finding Employee entities - entity selection --");
      EntityManager em = entityManagerFactory.createEntityManager();
      CriteriaBuilder cb = em.getCriteriaBuilder();
      CriteriaQuery<Employee> query = cb.createQuery(Employee.class);
      Root<Employee> employee = query.from(Employee.class);
      query.select(employee);
      TypedQuery<Employee> typedQuery = em.createQuery(query);
      List<Employee> resultList = typedQuery.getResultList();
      resultList.forEach(System.out::println);
      em.close();
  }

  private static void findEmployeeBySalaries() {
      System.out.println("-- Employee with salaries --");
      EntityManager entityManager = entityManagerFactory.createEntityManager();
      CriteriaBuilder cb = entityManager.getCriteriaBuilder();
      CriteriaQuery<Tuple> query = cb.createTupleQuery();
      Root<Employee> employee = query.from(Employee.class);
      query.multiselect(employee.get(Employee_.name).alias("employeeName"),
              employee.get(Employee_.salary).alias("salary"));
      TypedQuery<Tuple> typedQuery = entityManager.createQuery(query);
      List<Tuple> resultList = typedQuery.getResultList();
      for (Tuple tuple : resultList) {
          String employeeName = tuple.get("employeeName", String.class);
          Double salary = tuple.get("salary", Double.class);
          System.out.printf("name: %s, salary: %5.0f%n", employeeName, salary);
      }
      entityManager.close();
  }
}
-- finding Employee entities - entity selection --
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'}
-- Employee with salaries --
name: Diana, salary: 2000
name: Rose, salary: 4500
name: Denise, salary: 2000
name: Mike, salary: 4000
name: Linda, salary: 4500

Example Project

Dependencies and Technologies Used:

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

Selection#alias() Example Select All Download
  • jpa-criteria-api-selection-item-alias
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also