Updated April 1, 2023
Introduction to Hibernate Criteria
Hibernate Criteria Query Language (HCQL): Manipulating objects and available in turn data in RDBMS tables is provided in alternate ways by Hibernate. Of all, one method is called Criteria API. This allows us to build up a query criteria object programmatically. This can be used to apply rules of filtration and conditions applied logically. The session interface of hibernate provides createCriteria() method. This method can be used in creating Criteria objects. The object returns instances of persistence and object class. This happens when the execution of query criteria application is done. In this query language provides the methods which can add criteria and makes it easy for java programmers.
Syntax of Hibernate Criteria Query Language ( By Session Interface ) :
public Criteria createCriteria( class c )
How Hibernate Criteria Works?
Criteria Interface: The interface provides as many methods to specify the criteria. When you call createCriteria() method, the object of Criteria is obtained from the interface – Session.
The most common methods used of criteria interface are listed below:
Methods of Hibernate Criteria
- Public Criteria add ( Criterion c ): Method used to Add restrictions.
- public Criteria setMaxResult ( int ResultTotal ): Method which specifies the total number of records that are to be retrieved.
- public Criteria setFirstResult ( int firstResult ): Method used in specifying the first number of records that are to be retrieved.
- public Criteria addOrder ( Order o ): Method used in specifying ordering.
- public List_ list(): Method used in returning list which contains object.
- public Criteria setProjection ( Projection projection ): Method used in specifying the projection.
Example
An example where an application class is created with a main method and Criteria queries are used in running the application:
Code:
import java.util.List;
import java.util.Date;
import java.util.Iterator;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Projections;
import org.hibernate.cfg.Configuration;
public class ManageEmployee {
private static SessionFactory factory;
public static void main(String[] args) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
ManageEmployee ME = new ManageEmployee();
/* Few employee records are added in database */
Integer empID1 = ME.addEmployee("Zara", "Ali", 2000);
Integer empID2 = ME.addEmployee("Daisy", "Das", 5000);
Integer empID3 = ME.addEmployee("John", "Paul", 5000);
Integer empID4 = ME.addEmployee("Mohd", "Yasee", 3000);
/* Listing all the employees */
ME.listEmployees();
/* Total employee count is being printed */
ME.countEmployee();
/* Total salary is being printed */
ME.totalSalary();
}
/* CREATE employee in the database */
public Integer addEmployee(String fname, String lname, int salary){
Session session = factory.openSession();
Transaction tx = null;
Integer employeeID = null;
try {
tx = session.beginTransaction();
Employee employee = new Employee(fname, lname, salary);
employeeID = (Integer) session.save(employee);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
return employeeID;
}
/* READ employees who have salary > than 2000 */
public void listEmployees( ) {
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Employee.class);
// Add restriction.
cr.add(Restrictions.gt("salary", 2000));
List employees = cr.list();
for (Iterator iterator = employees.iterator(); iterator.hasNext();){
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFirstName());
System.out.print(" Last Name: " + employee.getLastName());
System.out.println(" Salary: " + employee.getSalary());
}
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/* Print total number of records */
public void countEmployee(){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Employee.class);
// To get the total row count.
cr.setProjection(Projections.rowCount());
List rowCount = cr.list();
System.out.println("Total Count: " + rowCount.get(0) );
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
/* Method to print sum of salaries */
public void totalSalary(){
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Criteria cr = session.createCriteria(Employee.class);
// To get a total salary.
cr.setProjection(Projections.sum("salary"));
List totalSalary = cr.list();
System.out.println("Total Salary: " + totalSalary.get(0) );
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Output:
The records are created in the employee table like this:
Now, the employee table will be containing the following records :
Conclusion
The best part of hibernate is the Criteria API. Developers prefer Criteria Query API over HQL and native SQL queries, even though it is not so difficult. Compile time syntax check is one in programmatic behaviour.
org.hibernate. Criteria interface package provides and defines many methods to create query objects programmatically.
Recommended Articles
This is a guide to Hibernate Criteria. Here we discuss how Hibernate Criteria Works and its Examples along with its Code Implementation. You can also go through our other suggested articles to learn more –