SlideShare a Scribd company logo
Hibernate
GETTING STARTED WITH HIBERNATE CRITERIA
- BY GAURAV KUMAR
Introduction
 The Criteria API allows us to build up a criteria query object programmatically, where we can apply
different kind of filtration rules and logical conditions. And the Session provides the createCriteria()
API – which can be used to create a Criteria object that returns instances of the persistence object’s
class when we execute a query.
Sample Class for Examples
public class Item implements Serializable {
private Integer itemId;
private String itemName;
private String itemDescription;
private Integer itemPrice;
// standard setters and getters
}
How to create criteria Object?
Session session = HibernateUtil.getHibernateSession();
Criteria cr = session.createCriteria(Item.class);
cr.add(Restrictions.like("itemName", "%item One%"));
List results = cr.list();
 The above query is a simple demonstration of how to get all the items. Let’s see what was done, step by
step:
 Create a session object of type Session
 Create an instance of Session from the SessionFactory object
 Create an instance of Criteria by calling the createCriteria() method
 Call the list() method of the criteria object which gives us the results
Sample Codes?
The add() method can be used with Criteria object to add restriction for a criteria query. For that we also need to use the Restriction class.
The following code snippet of code contains all the available functionalities available with Restriction class:
To get items having price more than 1000: cr.add(Restrictions.gt("itemPrice", 1000));
To get items having itemPrice less than 1000: cr.add(Restrictions.lt("itemPrice", 1000));
To get items having itemNames start with Chair: cr.add(Restrictions.like("itemName", "chair%"));
Case sensitive form of the above restriction: cr.add(Restrictions.ilike("itemName", "Chair%"));
Case sensitive with matching the pattern in between: cr.add(Restrictions.ilike("itemName", "Chair%“, MatchMode.ANYWHERE));
To get records having itemPrice in between 100 and 200: cr.add(Restrictions.between("itemPrice", 100, 200));
To check if the given property is null: cr.add(Restrictions.isNull("itemDescription"));
To check if the given property is not null: cr.add(Restrictions.isNotNull("itemDescription"));
What if I want to add two or more conditions???
Now inevitably the question comes, whether we can combine two or more of the above comparisons or not. The answer is of
course yes – the Criteria API allows us to easily chain restrictions:
cr.add(Restrictions.isNotEmpty("itemDescription")).add(Restrictions.like("itemName", "chair%"));
To add two restrictions with logical operations:
Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000);
Criterion chairItems = Restrictions.like("itemName", "Chair%");
To get items with the above defined conditions joined with Logical OR:
LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems);
cr.add(orExample);
Sorting of the result
Now that we know the basic usage of Criteria, let’s have a look at the sorting functionalities of Criteria.
In the following example we order the list in an ascending order of the name and then in a descending order of the price:
List sortedItems = cr.addOrder(Order.asc("itemName")).addOrder(Order.desc("itemPrice")).list();
In the next section we will have a look at how to do aggregate functions.
Projections, Aggregates And Grouping
Functions
Now let’s have a look at the different aggregate functions:
Set projections:
List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).add( Restrictions.eq("itemPrice",
12000)).list();
The following is an example of aggregate functions:
Aggregate function for Average:
List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList()
.add(Projections.avg("itemPrice"))).list();
Advantages over HQL???
ANY GUESS???
Here are some of the advantages???
 Clearly, the main and most hard-hitting advantage of Criteria queries over HQL is the nice,
clean, Object Oriented API.
 We can simply write more flexible, dynamic queries compared to plain HQL. The logic can be
refactored with the IDE and has all the type-safety benefits of the Java language itself.
 There are of course some disadvantages as well, especially around more complex joins.
 So, generally speaking, we’ll have to use the best tool for the job – that can be the Criteria API in
most cases, but there are definitely cases where we’ll have to go lower level.
Questions???
 Feel free to write : gaurav.5410@gmail.com.

More Related Content

PPT
Hibernate Tutorial
PPT
Introduction to hibernate
PPT
Intro To Hibernate
PDF
Hibernate An Introduction
PPT
hibernate with JPA
PPTX
Hibernate in Nutshell
PPTX
Hibernate
Hibernate Tutorial
Introduction to hibernate
Intro To Hibernate
Hibernate An Introduction
hibernate with JPA
Hibernate in Nutshell
Hibernate

What's hot (20)

ODP
JavaEE Spring Seam
ODP
Hibernate complete Training
PPT
Java Persistence API (JPA) Step By Step
ODP
Java Persistence API
PPTX
Introduction to Hibernate Framework
PPT
Entity Persistence with JPA
PDF
Java persistence api 2.1
PDF
Introduction to JPA and Hibernate including examples
PDF
Filtering data with D2W
PDF
PDF
Spring Data JPA
PPTX
ODP
JPA Best Practices
PPTX
Hibernate Basic Concepts - Presentation
PPTX
Easy data-with-spring-data-jpa
PPTX
Hibernate ppt
PPT
jpa-hibernate-presentation
PDF
JPA and Hibernate
PPTX
Spring (1)
PPTX
Introduction to JPA (JPA version 2.0)
JavaEE Spring Seam
Hibernate complete Training
Java Persistence API (JPA) Step By Step
Java Persistence API
Introduction to Hibernate Framework
Entity Persistence with JPA
Java persistence api 2.1
Introduction to JPA and Hibernate including examples
Filtering data with D2W
Spring Data JPA
JPA Best Practices
Hibernate Basic Concepts - Presentation
Easy data-with-spring-data-jpa
Hibernate ppt
jpa-hibernate-presentation
JPA and Hibernate
Spring (1)
Introduction to JPA (JPA version 2.0)
Ad

Viewers also liked (20)

PPTX
Hibernate inheritance and relational mappings with examples
PDF
Hibernate Presentation
PDF
Spring and hibernate santosh'.pdf
PPT
Spring hibernate tutorial
PPT
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
PDF
Профессиональная разработка в суровом Enterprise
PDF
Orm на no sql через jpa. Павел Вейник
PDF
Spring Framework - Validation
PDF
Spring Framework - Data Access
PDF
Transactions and Concurrency Control Patterns
PDF
Spring Framework - Expression Language
PPTX
Hibernate in Action
PDF
Spring Framework - Web Flow
PPTX
Spring & hibernate
PDF
High-Performance Hibernate Devoxx France 2016
PDF
Hibernate ORM: Tips, Tricks, and Performance Techniques
PPS
Java Hibernate Programming with Architecture Diagram and Example
ODP
ORM, JPA, & Hibernate Overview
PDF
Spring Framework - MVC
PDF
Spring Framework - Spring Security
Hibernate inheritance and relational mappings with examples
Hibernate Presentation
Spring and hibernate santosh'.pdf
Spring hibernate tutorial
ZFConf 2011: Толстая модель: История разработки собственного ORM (Михаил Шамин)
Профессиональная разработка в суровом Enterprise
Orm на no sql через jpa. Павел Вейник
Spring Framework - Validation
Spring Framework - Data Access
Transactions and Concurrency Control Patterns
Spring Framework - Expression Language
Hibernate in Action
Spring Framework - Web Flow
Spring & hibernate
High-Performance Hibernate Devoxx France 2016
Hibernate ORM: Tips, Tricks, and Performance Techniques
Java Hibernate Programming with Architecture Diagram and Example
ORM, JPA, & Hibernate Overview
Spring Framework - MVC
Spring Framework - Spring Security
Ad

Similar to Hibernate working with criteria- Basic Introduction (20)

PPT
08 Queries
PPT
Hibernate for Beginners
PPT
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
PDF
Hibernate III
PDF
Enhancing Spark SQL Optimizer with Reliable Statistics
PDF
Cost-Based Optimizer Framework for Spark SQL: Spark Summit East talk by Ron H...
PPTX
Grails queries
PDF
Tech Talk - JPA and Query Optimization - publish
PPTX
nHibernate Query
PPTX
Session 40 - Hibernate - Part 2
PDF
Cost-Based Optimizer in Apache Spark 2.2
PDF
Cost-Based Optimizer in Apache Spark 2.2 Ron Hu, Sameer Agarwal, Wenchen Fan ...
PDF
Hibernate 6.1 - What's new.pdf
PDF
Finding Love with MongoDB
PDF
Java 8 new features or the ones you might actually use
PDF
Hibernate 6.0 - What's new.pdf
PPT
04 Data Access
PPTX
ActionScript3 collection query API proposal
PPTX
Advanced criteria queries
08 Queries
Hibernate for Beginners
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Hibernate III
Enhancing Spark SQL Optimizer with Reliable Statistics
Cost-Based Optimizer Framework for Spark SQL: Spark Summit East talk by Ron H...
Grails queries
Tech Talk - JPA and Query Optimization - publish
nHibernate Query
Session 40 - Hibernate - Part 2
Cost-Based Optimizer in Apache Spark 2.2
Cost-Based Optimizer in Apache Spark 2.2 Ron Hu, Sameer Agarwal, Wenchen Fan ...
Hibernate 6.1 - What's new.pdf
Finding Love with MongoDB
Java 8 new features or the ones you might actually use
Hibernate 6.0 - What's new.pdf
04 Data Access
ActionScript3 collection query API proposal
Advanced criteria queries

Recently uploaded (20)

PDF
01-Introduction-to-Information-Management.pdf
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Institutional Correction lecture only . . .
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Cell Structure & Organelles in detailed.
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Cell Types and Its function , kingdom of life
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Classroom Observation Tools for Teachers
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PPTX
master seminar digital applications in india
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
01-Introduction-to-Information-Management.pdf
Chinmaya Tiranga quiz Grand Finale.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Institutional Correction lecture only . . .
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
A systematic review of self-coping strategies used by university students to ...
Complications of Minimal Access Surgery at WLH
Cell Structure & Organelles in detailed.
Pharma ospi slides which help in ospi learning
Cell Types and Its function , kingdom of life
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Microbial disease of the cardiovascular and lymphatic systems
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Supply Chain Operations Speaking Notes -ICLT Program
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Classroom Observation Tools for Teachers
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
master seminar digital applications in india
2.FourierTransform-ShortQuestionswithAnswers.pdf

Hibernate working with criteria- Basic Introduction

  • 1. Hibernate GETTING STARTED WITH HIBERNATE CRITERIA - BY GAURAV KUMAR
  • 2. Introduction  The Criteria API allows us to build up a criteria query object programmatically, where we can apply different kind of filtration rules and logical conditions. And the Session provides the createCriteria() API – which can be used to create a Criteria object that returns instances of the persistence object’s class when we execute a query.
  • 3. Sample Class for Examples public class Item implements Serializable { private Integer itemId; private String itemName; private String itemDescription; private Integer itemPrice; // standard setters and getters }
  • 4. How to create criteria Object? Session session = HibernateUtil.getHibernateSession(); Criteria cr = session.createCriteria(Item.class); cr.add(Restrictions.like("itemName", "%item One%")); List results = cr.list();  The above query is a simple demonstration of how to get all the items. Let’s see what was done, step by step:  Create a session object of type Session  Create an instance of Session from the SessionFactory object  Create an instance of Criteria by calling the createCriteria() method  Call the list() method of the criteria object which gives us the results
  • 5. Sample Codes? The add() method can be used with Criteria object to add restriction for a criteria query. For that we also need to use the Restriction class. The following code snippet of code contains all the available functionalities available with Restriction class: To get items having price more than 1000: cr.add(Restrictions.gt("itemPrice", 1000)); To get items having itemPrice less than 1000: cr.add(Restrictions.lt("itemPrice", 1000)); To get items having itemNames start with Chair: cr.add(Restrictions.like("itemName", "chair%")); Case sensitive form of the above restriction: cr.add(Restrictions.ilike("itemName", "Chair%")); Case sensitive with matching the pattern in between: cr.add(Restrictions.ilike("itemName", "Chair%“, MatchMode.ANYWHERE)); To get records having itemPrice in between 100 and 200: cr.add(Restrictions.between("itemPrice", 100, 200)); To check if the given property is null: cr.add(Restrictions.isNull("itemDescription")); To check if the given property is not null: cr.add(Restrictions.isNotNull("itemDescription"));
  • 6. What if I want to add two or more conditions??? Now inevitably the question comes, whether we can combine two or more of the above comparisons or not. The answer is of course yes – the Criteria API allows us to easily chain restrictions: cr.add(Restrictions.isNotEmpty("itemDescription")).add(Restrictions.like("itemName", "chair%")); To add two restrictions with logical operations: Criterion greaterThanPrice = Restrictions.gt("itemPrice", 1000); Criterion chairItems = Restrictions.like("itemName", "Chair%"); To get items with the above defined conditions joined with Logical OR: LogicalExpression orExample = Restrictions.or(greaterThanPrice, chairItems); cr.add(orExample);
  • 7. Sorting of the result Now that we know the basic usage of Criteria, let’s have a look at the sorting functionalities of Criteria. In the following example we order the list in an ascending order of the name and then in a descending order of the price: List sortedItems = cr.addOrder(Order.asc("itemName")).addOrder(Order.desc("itemPrice")).list(); In the next section we will have a look at how to do aggregate functions.
  • 8. Projections, Aggregates And Grouping Functions Now let’s have a look at the different aggregate functions: Set projections: List itemProjected = session.createCriteria(Item.class).setProjection(Projections.rowCount()).add( Restrictions.eq("itemPrice", 12000)).list(); The following is an example of aggregate functions: Aggregate function for Average: List avgItemPriceList = session.createCriteria(Item.class).setProjection(Projections.projectionList() .add(Projections.avg("itemPrice"))).list();
  • 10. Here are some of the advantages???  Clearly, the main and most hard-hitting advantage of Criteria queries over HQL is the nice, clean, Object Oriented API.  We can simply write more flexible, dynamic queries compared to plain HQL. The logic can be refactored with the IDE and has all the type-safety benefits of the Java language itself.  There are of course some disadvantages as well, especially around more complex joins.  So, generally speaking, we’ll have to use the best tool for the job – that can be the Criteria API in most cases, but there are definitely cases where we’ll have to go lower level.
  • 11. Questions???  Feel free to write : gaurav.5410@gmail.com.