Hibernate Restrictions Example | Restrictions in Hibernate

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
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.
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.
If we want to read employees, who are working in department 101, then a condition can be added like the following:
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.
If we want to add, 2 or more conditions using Hibernate Restrictions, both conditions are added like below:
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);
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
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
<?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
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 :
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 🙂


Hibernate-Restrictions-Example

File size: 13 KB
Downloads: 725


Hibernate Projection with Example
Hibernate Criteria API with Example
Hibernate Filters Example Annotation
Calling Stored Procedures in Hibernate
Hibernate Query Language (HQL) Select Operation
@Formula Annotation in Hibernate Example
Dependency Injection (IoC) in spring with Example
Hibernate Right Join Example
BeanFactory Example in Spring
hibernate update query example
hbm2ddl.auto Example in Hibernate XML Config
Hibernate sql dialect list
What is Association in Java
Hibernate Native SQL Query Example
Hibernate groupby criteria HQL query Example

Hibernate Projection with Example
Hibernate Criteria API with Example
Hibernate Filters Example Annotation
Calling Stored Procedures in Hibernate
Hibernate Query Language (HQL) Select Operation
@Formula Annotation in Hibernate Example
Dependency Injection (IoC) in spring with Example
Hibernate Right Join Example
BeanFactory Example in Spring
hibernate update query example
hbm2ddl.auto Example in Hibernate XML Config
Hibernate sql dialect list
What is Association in Java
Hibernate Native SQL Query Example
Hibernate groupby criteria HQL query Example
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache