Hibernate Criteria Example | Hibernate Criteria Tutorials Point

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 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 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 :
Creating Employee Pojo :
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 :
<?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
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 :
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]
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]);
        }
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 🙂


Hibernate-CriteriaAPI-Example

File size: 14 KB
Downloads: 921


Hibernate Restrictions with Example
Hibernate Filters Example Annotation
@Formula Annotation in Hibernate Example
Hibernate Filter Example Xml Configuration
Hibernate Native SQL Query Example
hibernate update query example
Hibernate One to One Mapping using primary key (XML)
Hibernate orderby criteria Example
Hibernate groupby criteria HQL query Example
What is Hibernate
Hibernate 4 Example with Annotations Mysql
Different types of Object States in Hibernate
Difference between update vs merge in Hibernate example
Hibernate cache first level example
Table per Class Strategy in Hibernate Inheritance

Hibernate Restrictions with Example
Hibernate Filters Example Annotation
@Formula Annotation in Hibernate Example
Hibernate Filter Example Xml Configuration
Hibernate Native SQL Query Example
hibernate update query example
Hibernate One to One Mapping using primary key (XML)
Hibernate orderby criteria Example
Hibernate groupby criteria HQL query Example
What is Hibernate
Hibernate 4 Example with Annotations Mysql
Different types of Object States in Hibernate
Difference between update vs merge in Hibernate example
Hibernate cache first level example
Table per Class Strategy in Hibernate Inheritance






Elvin Antonio Mendoza
September 11, 2019 at 2:21 am - Reply 

Thank you for your help, I was looking for  a lot of site for find a good information to resolve a problem with how to use hibernate correctly. Tnak you so much And I hope that you are ok.










Elvin Antonio Mendoza
September 11, 2019 at 2:21 am - Reply 

Thank you for your help, I was looking for  a lot of site for find a good information to resolve a problem with how to use hibernate correctly. Tnak you so much And I hope that you are ok.




Thank you for your help, I was looking for  a lot of site for find a good information to resolve a problem with how to use hibernate correctly. Tnak you so much And I hope that you are ok.
 


Δ
 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