In this tutorials, we are going to learn about Hibernate Restrictions with Example. In the previous tutorial we had a detailed discussion about Hibernate Projections and how to use them. Coming to the Hibernate Restrictions, if we want to apply a condition in criteria query, then we can use Restrictions.

Bullet points about Hibernate Restrictions :

  • If we want to apply a condition to criteria query, we need Criterion object.
  • Criterion is an interface, it is an object-oriented representation of a query criterion that may be used as a restriction in a Criteria query.
  • We can obtain the Criterion type objects, by calling static methods of Restrictions class.
  • Restrictions is a normal Java class, which doesn’t implement any Criterion interface.
  • Criterion interface and Restrictions class, both are coming from org.hibernate.criterion package.

Hibernate Restrictions Example :

If we want to read employees, who are working in department 101, then a condition can be added like the following:

Criteria
Criteria criteria = session.createCriteria(Employee.class);
Criterion criterion = Restrictions.eq("departmentId", 101);
criteria.add(criterion);

On the above example, we are trying to get the employees who are working in department 101. This is exactly like select * from emp where deptno=101 in SQL.

Adding multiple conditions :

If we want to add, 2 or more conditions using Hibernate Restrictions, both conditions are added like below:

Criteria with multiple conditions
Criteria criteria = session.createCriteria(Employee.class);
Criterion criterion = Restrictions.eq("departmentId", 101);
Criterion criterion2 = Restrictions.gt("salary", 4000);
Criterion criterion3 = Restrictions.and(criterion,criterion2);
criteria.add(criterion3);

In the above example, we are trying to get the employees information, who are working in department id = 101 and salary > 4000. This is exactly like select * from emp where deptid=101 and salary > 4000 in SQL. Restrictions class has and() method to apply the ‘and condition’ in a query. We can add variable number of conditions in and() method like and(criterion,criterion-2,criterion-3,…..,criterion-n);

Important methods in Hibernate Restrictions :

  • between(String propertyName, Object lo, Object hi)
    Apply a “between” constraint to the named property
  • eq(String propertyName, Object value)
    Apply an “equal” constraint to the named property
  • ge(String propertyName, Object value)
    Apply a “greater than or equal” constraint to the named property
  • gt(String propertyName, Object value)
    Apply a “greater than” constraint to the named property
  • ilike(String propertyName, Object value)
    A case-insensitive “like”, similar to Postgres ilike operator
  • in(String propertyName, Object[] values)
    Apply an “in” constraint to the named property
  • le(String propertyName, Object value)
    Apply a “less than or equal” constraint to the named property
  • like(String propertyName, Object value)
    Apply a “like” constraint to the named property
  • lt(String propertyName, Object value)
    Apply a “less than” constraint to the named property
  • ne(String propertyName, Object value)
    Apply a “not equal” constraint to the named property
  • or(Criterion lhs, Criterion rhs)
    Return the disjuction of two expressions

Hibernate Restrictions Example :

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 + "]";
    }
}

employee.hbm.xml

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>

Main.java

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 with Condition");

        Criteria criteria = session.createCriteria(Employee.class);
        Criterion criterion = Restrictions.eq("departmentId", 101);
        Criterion criterion2 = Restrictions.gt("salary", 4000);
        Criterion criterion3 = Restrictions.and(criterion,criterion2);

        criteria.add(criterion3);
        
        List list = criteria.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 with Condition
Employee : Employee [employeeId=1, employeeName=Chandra, departmentId=101, salary=6000]
Employee : Employee [employeeId=2, employeeName=Shekhar, departmentId=101, salary=8000]

Complete example is available for download.

Happy Learning 🙂

Download Example