Close

JPA Criteria API - Selecting User defined Objects using CriteriaBuilder#construct()

[Last Updated: Mar 4, 2019]

To return user defined objects (not entities) as query results we can use CriteriaBuilder#construct():

<Y> CompoundSelection<Y> construct(Class<Y> resultClass, Selection<?>... selections);

For example:

    CriteriaQuery<EmployeeInfo> query = criteriaBuilder.createQuery(EmployeeInfo.class);
    Root<Employee> employee = query.from(Employee.class);
    query.select(criteriaBuilder.construct(EmployeeInfo.class, employee.get(Employee_.name),
                                                             employee.get(Employee_.salary)));
    List<EmployeeInfo> resultList = entityManager.createQuery(query).getResultList();

Criteriabuilder#construct() is equivalent to JPQL constructor expressions.

Alternatively we can use CriteriaQuery#multiselect():

    CriteriaQuery<EmployeeInfo> query = cb.createQuery(EmployeeInfo.class);
    Root<Employee> employee = query.from(Employee.class);
    query.multiselect(employee.get(Employee_.name), employee.get(Employee_.salary));
    List<EmployeeInfo> resultList = em.createQuery(query).getResultList();

According to CriteriaQuery#multiselect(selections) document:

If the type of the criteria query is CriteriaQuery<X> for some user-defined class X (i.e., a criteria query object created by passing a X class argument to the createQuery method), the arguments to the multiselect method will be passed to the X constructor and an instance of type X will be returned for each row.
If the type of the criteria query is CriteriaQuery<X[]> for some class X, an instance of type X[] will be returned for each row. The elements of the array will correspond to the arguments of the multiselect method, in the specified order.

Example

Entity

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

Non-entity user defined class

public class EmployeeInfo {
    private String name;
    private double salary;

    public EmployeeInfo(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }
    .............
}

Using construct() method

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

    public static void main(String[] args) {
        try {
            persistEmployees();
            findAllEmployeeEntities();
            findEmployeeInfo();
            findEmployeeInfo2();
        } 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 findEmployeeInfo() {
        System.out.println("-- EmployeeInfo - using construct() --");
        EntityManager em = entityManagerFactory.createEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<EmployeeInfo> query = cb.createQuery(EmployeeInfo.class);
        Root<Employee> employee = query.from(Employee.class);
        query.select(cb.construct(EmployeeInfo.class, employee.get(Employee_.name),
                employee.get(Employee_.salary)));
        TypedQuery<EmployeeInfo> typedQuery = em.createQuery(query);
        List<EmployeeInfo> resultList = typedQuery.getResultList();
        resultList.forEach(System.out::println);
        em.close();
    }

    private static void findEmployeeInfo2() {
        System.out.println("-- EmployeeInfo - using multiselect() --");
        EntityManager em = entityManagerFactory.createEntityManager();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<EmployeeInfo> query = cb.createQuery(EmployeeInfo.class);
        Root<Employee> employee = query.from(Employee.class);
        query.multiselect(employee.get(Employee_.name),
                employee.get(Employee_.salary));
        TypedQuery<EmployeeInfo> typedQuery = em.createQuery(query);
        List<EmployeeInfo> resultList = typedQuery.getResultList();
        resultList.forEach(System.out::println);
        em.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'}
-- EmployeeInfo - using construct() --
EmployeeInfo{name='Diana', salary=2000.0}
EmployeeInfo{name='Rose', salary=4500.0}
EmployeeInfo{name='Denise', salary=2000.0}
EmployeeInfo{name='Mike', salary=4000.0}
EmployeeInfo{name='Linda', salary=4500.0}
-- EmployeeInfo - using multiselect() --
EmployeeInfo{name='Diana', salary=2000.0}
EmployeeInfo{name='Rose', salary=4500.0}
EmployeeInfo{name='Denise', salary=2000.0}
EmployeeInfo{name='Mike', salary=4000.0}
EmployeeInfo{name='Linda', salary=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

CriteriaBuilder#construct() Example Select All Download
  • jpa-criteria-api-construct
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also