Close

JPA Criteria API - Using Metamodel to create type safe queries

[Last Updated: Jul 7, 2018]

In the last tutorial we used Criteria API along with string based attribute references, i.e.

     Root<Employee> employee = query.from(Employee.class);
     query.select(employee)
          .where(cb.equal(employee.get("dept"), "Admin"));

Here we have another option, JPA allows to automatically generate metamodel class for each entity class. If entity is T then it's metamodel class is generated as T_ which can be used to reference attributes in a strongly typed manner:

    Root<Employee> employee = query.from(Employee.class);
    query.select(employee)
         .where(cb.equal(employee.get(Employee_.dept), "Admin"));

Example

Entity

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

Additional maven dependencies

pom.xml

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-jpamodelgen</artifactId>
   <version>5.3.2.Final</version>
</dependency>

Hibernate JPA Metamodel Generator

We also need to specify Hibernate annotation processor which is responsible to generate the metamodel for the entities:

 <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <compilerArguments>
                        <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
                    </compilerArguments>
                </configuration>
            </plugin>
        </plugins>
    </build>

Compiling

We need to compile our entity class for above processor to work. Employee_ will be generated at following location (screenshot from IntelliJ):

The generated class Employee_

package com.logicbig.example;

import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;

@StaticMetamodel(Employee.class)
public abstract class Employee_ {
    public static volatile SingularAttribute<Employee, String> name;
    public static volatile SingularAttribute<Employee, Long> id;
    public static volatile SingularAttribute<Employee, String> dept;
    public static volatile SingularAttribute<Employee, Double> salary;
    public static final String NAME = "name";
    public static final String ID = "id";
    public static final String DEPT = "dept";
    public static final String SALARY = "salary";

    public Employee_() {
    }
}

Using Criteria API

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

    public static void main(String[] args) {
        try {
            persistEmployees();
            findAdmins();
        } 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 findAdmins() {
        System.out.println("-- All employees with salary greater than 3000 --");
        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)
             .where(cb.gt(employee.get(Employee_.salary), 3000d));
        TypedQuery<Employee> typedQuery = em.createQuery(query);
        typedQuery.getResultList()
                  .forEach(System.out::println);
        em.close();
    }
}
-- All employees with salary greater than 3000 --
Employee{id=2, name='Rose', salary=3500.0, dept='Admin'}
Employee{id=4, name='Mike', salary=4000.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

Using Metamodel to create type safe queries Select All Download
  • jpa-criteria-api-with-metamodel
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • ExampleMain.java
          • resources
            • META-INF

    See Also