Hibernate Criteria Query

Hibernate Criteria Query API lets you create nested, structured query expressions in Java, it gives you an object oriented control over the queries, it provides a compile time syntax check which is not possible with a query language like HQL or SQL.

Since Hibernate 5.2, the Hibernate Criteria API is deprecated and 
new development is focused on the JPA Criteria API.

Hibernate version that We are using here :

<dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-core</artifactId>
     <version>5.4.11.Final</version>
</dependency>

Hibernate Criteria Query : Example

Employee Entity

@Entity
@Table(name = "Employee")
public class Employee implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "address")
    private String address;

// getters & setters & toString()
// ...
}

Fetch Employees from the Database using Criteria Query

// Criteria Query Example
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Employee> cr = cb.createQuery(Employee.class);
Root<Employee> root = cr.from(Employee.class);
cr.select(root);

Query criteriaQuery = session.createQuery(cr);
List<Employee> results = query.getResultList();
results.forEach(System.out::println); // print all Employee records

Explanation Step by Step :

  1. Create an instance of Session from the SessionFactory object
  2. Create an instance of CriteriaBuilder by calling the getCriteriaBuilder() method
  3. Create an instance of CriteriaQuery by calling the CriteriaBuilder createQuery() method
  4. Create an instance of Query by calling the Session createQuery() method
  5. Call the getResultList() method of the query object which gives us the results
  6. At last using java 8 for each loop to print the records.

Summary

In this tutorial, we focused on the basics of Criteria Queries in Hibernate and JPA,
Hope you liked it !


Leave a Comment