EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Hibernate Criteria

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Hibernate Tutorial » Hibernate Criteria

Hibernate Criteria

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 ) :

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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

Output:

The records are created in the employee table like this:

Hibernate Criteria Example 1

Now, the employee table will be containing the following records :

 Hibernate Criteria Example 2

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.

Popular Course in this category
Hibernate course (4 Courses, 4 Projects)4 Online Courses | 4 Hands-on Project | 32+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (3,305 ratings)
Course Price

View Course

Related Courses

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 –

  1. Cascade in Hibernate
  2. Hibernate Versions
  3. Hibernate Tools
  4. Hibernate Many to Many

Hibernate course (4 Courses, 4 Projects)

4 Online Courses

4 Hands-on Project

32+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Hibernate Tutorial
  • Basic
    • What is Hibernate
    • What is Java Hibernate
    • Hibernate Versions
    • Hibernate Architecture
    • Hibernate Framework
    • Hibernate Tools
    • Hibernate Annotations
    • Hibernate Mapping
    • Hibernate Many to One
    • Hibernate Many to Many
    • Hibernate Dialect
    • Hibernate Session
    • Hibernate SessionFactory
    • Lazy Loading in Hibernate
    • Hibernate Criteria
    • Hibernate Persist
    • Hibernate EntityManager
    • Caching in Hibernate
    • Cascade in Hibernate
    • Hibernate Generator
    • Hibernate Validator
    • Spring Hibernate Integration
    • Hibernate Query Language
    • Hibernate Named Query
    • Hibernate Interview Questions
    • HQL
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Hibernate course (4 Courses, 4 Projects) Learn More