Explain Works of Hibernate Criteria

Explain Works of Hibernate Criteria
Techiio-author
Written by Sagar RabidasFebruary 16, 2022
7 min read
Hibernate
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

Today start the discussion with Hibernate Criteria

Introduction of Hibernate Criteria:-

Hibernate Criteria Query Language (HCQL): manipulating objects and to be had in flip records in RDBMS tables is supplied in change ways using hibernate. Of all, one method is called criteria API. This permits us to accumulate question criteria object programmatically. This could be used to apply guidelines of filtration and situations applied logically. The session interface of hibernating offers creates standards() technique. This technique can be used in developing criteria items. The item returns times of endurance and item elegance. This takes place when the execution of the query standards software is accomplished. This query language gives the methods that may upload criteria and makes it easy for java programmers.

Syntax of Hibernate Criteria Query Language ( By Session Interface ) :
public Criteria create criteria( class c )

How Hibernate Criteria Works:-

Criteria Interface: The interface provides as many methods to specify the criteria. When you call create criteria() method, the object of Criteria is obtained from the interface – Session.

The most common methods used of criteria interface are listed below:

Methods and Examples of Hibernate Criteria:-

  1. Public Criteria add ( Criterion c ): Method used to Add restrictions.
  2. public Criteria set a result ( int ResultTotal ): Method which specifies the total number of records that are to be retrieved.
  3. public Criteria setFirstResult ( int firstResult ): Method used in specifying the first number of records that are to be retrieved.
  4. public Criteria add order ( Order o ): Method used in specifying orders.
  5. public List_ list(): Method used in returning list which contains the object.
  6. public Criteria set projection ( Projection projection ): Method used in specifying the projection.

Example of Hibernate Criteria:

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();
}
}
}

Hibernate
Hibernate Criteria
Java
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+8 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance