In this tutorial, we are going to learn about Hibernate Criteria API. While working with Hibernate Query Language (HQL), we manually prepare the HQL queries for reading the data from database. For the better performance, it is always recommended to write a query as tuned query.

In the case of HQL, we need to prepare the tuned queries. Hibernate will only translate HQL into SQL and then executes it, but it will not tune the queries. Here (HQL) the responsibility of tuning the queries on the developer.

Instead of writing the HQL queries and tuning them explicitly, we can use Hibernate Criteria API.

In the Hibernate Criteria API, there is no need to create a query. Instead, hibernate itself will prepare a tuned query. So that we can get better performance with criteria while reading the data from the database.

Query tuning is required only while selecting the data, so hibernate Criteria API is for select operations only.

Here is the complete example for hibernate criteria :

Hibernate Criteria Example :

Hibernate Criteria is an interface, it is a simplified API for retrieving entities. We can obtain a reference of Criteria interface by calling the createCriteria() method on the session by passing the object of a pojo class.
Criteria criteria = session.createCriteria(Employee.class);
Project Structure :

Hibernate criteria ExampleCreating Employee Pojo :

Employee.java

Employee.java
package com.otp.hibernate.pojo;

public class Employee {
    private int employeeId;
    private String employeeName;
    private int departmentId;
    private int salary;

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public int getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(int departmentId) {
        this.departmentId = departmentId;
    }

    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Employee [employeeId=" + employeeId + ", employeeName="
                + employeeName + ", departmentId=" + departmentId + ", salary="
                + salary + "]";
    }
}

Hibernate mapping file :

Employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.otp.hibernate.pojo.Employee" table="employee"
        schema="onlinetutorialspoint">
        <id name="employeeId" column="id">
            <generator class="increment" />
        </id>
        <property name="employeeName" column="ename" />
        <property name="departmentId" column="deptNo" />
        <property name="salary" column="salary" />
    </class>
</hibernate-mapping>

As we discussed in HQL example, we can read the data from database in three forms, like

  • Reading complete entity
  • Reading partial entity
  • Reading partial entity with single column

Hibernate Criteria Reading complete Entity :

Main.java
import java.util.Iterator;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.otp.hibernate.pojo.Employee;

public class Main {

    public static void main(String[] args) {
        Configuration configuration = new Configuration()
                .configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        SessionFactory factory = configuration.buildSessionFactory(builder
                .build());

        Session session = factory.openSession();

        System.out.println("Reading Complete Entity");

        Criteria crit = session.createCriteria(Employee.class);
        List list = crit.list();

        Iterator it = list.iterator();

        while (it.hasNext()) {
            Employee emp = (Employee) it.next();
            System.out.println("Employee : " + emp.toString());

        }

        session.close();
    }
}

 

Output :

Console
Reading Complete Entity
Employee : Employee [employeeId=1, employeeName=Chandra, departmentId=101, salary=6000]
Employee : Employee [employeeId=2, employeeName=Shekhar, departmentId=101, salary=8000]
Employee : Employee [employeeId=3, employeeName=Rahul, departmentId=105, salary=4000]
Employee : Employee [employeeId=4, employeeName=Mahesh, departmentId=103, salary=5000]
Employee : Employee [employeeId=5, employeeName=Vinay, departmentId=101, salary=4000]
Employee : Employee [employeeId=6, employeeName=Vijay, departmentId=105, salary=3000]

Hibernate Criteria Reading the partial Entity :

To read the partial entity, hibernate criteria provides us, Projection interface.

By using the Projection interface, we can set the columns as parameters, which we want to read.
Projection projection = Projections.property("salary");
Finally, we need to add the projection to criteria.
criteria.setProjection(projection);

If we want to read the multiple columns, we can create the multiple Projection instances like below :

Projection projection = Projections.property("salary");
Projection projection2 = Projections.property("departmentId");
Projection projection3 = Projections.property("employeeName");

Get the ProjectionsList object and add all projections to projectionslist object like below :

ProjectionList pList = Projections.projectionList();
pList.add(projection);
pList.add(projection2);
pList.add(projection3);

Complete Example :


Criteria crit3 = session.createCriteria(Employee.class);
        Projection projection = Projections.property("salary");
        Projection projection2 = Projections.property("departmentId");
        Projection projection3 = Projections.property("employeeName");

        ProjectionList pList = Projections.projectionList();
        pList.add(projection);
        pList.add(projection2);
        pList.add(projection3);
        crit3.setProjection(pList);

        List list3 = crit3.list();

        Iterator it3 = list3.iterator();

        while (it3.hasNext()) {
            Object[] obj = (Object[]) it3.next();
            System.out.println("Salary : " + obj[0] + " DeptId : " + obj[1]
                    + " empName : " + obj[2]);
        }

Adding condition to Hibernate Criteria :

To add a condition to criteria, hibernate provides us Criterion interface. We can obtain criterion object by calling the static methods of Restrictions class. To add the criterion object to criteria, we call add() method like below :

Criteria crit = session.createCriteria(Employee.class);

Criterion criterion = Restrictions.eq("departmentId", 101);

crit.add(criterion);

The above statements represents, get the employee records from database, whose department id is 101;

Complete Example :


Criteria crit2 = session.createCriteria(Employee.class);

        Criterion criterion = Restrictions.eq("departmentId", 101);

        crit2.add(criterion);

        List list2 = crit2.list();

        Iterator it2 = list2.iterator();

        while (it2.hasNext()) {
            Employee emp = (Employee) it2.next();
            System.out.println("Employee : " + emp.toString());
        }

The complete Example is available to download.

Happy Learning 🙂

Download Example