Table of contents
1.
Introduction
2.
Criteria API
2.1.
Creating a Criteria Instances
3.
Narrowing the result set with the Criteria
4.
Sorting the result set with Criteria
5.
Associations with Criteria
6.
Projections, aggregation, and grouping
7.
Pagination using criteria
8.
Example Queries
9.
Detached queries and subqueries
10.
Frequently Asked Questions
10.1.
What are the differences between Heap and Stack Memory in Java?
10.2.
Can you set Hibernate's Entity class as final?
10.3.
What is Projection in Hibernate?
10.4.
What is lazy loading in hibernate?
11.
Conclusion
Last Updated: Mar 27, 2024
Easy

Hibernate Criteria Basic Query

Author Ayush Mishra
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hibernate Criteria Basic Query is used for searching and retrieving records. It utilizes logical conditions and filtering rules to operate. The org.hibernate package contains the properties and methods to carry out Hibernate criteria basic query operations. It also includes the Criteria interface, Restriction class, and Order class.

In this blog, we will discuss the Hibernate Criteria basic query to get the data into the RDBMS tables. It is used to find the filter set according to to need and is similar to the “WHERE” clause in SQL.

Criteria API

The Criteria interface in Hibernate Criteria Basic Query  is contained in the org.hibernate package, which is used to create criterion objects to retrieve entities. According to the requirements, it is used to search for objects or data.

It is used to write typed queries programmatically, which helps us prevent syntax mistakes. It performs compile-time checks when used with the Metamodel API to ensure that the field names and types are correct.

When your application runs a criteria query, the createCriteria() function of the Hibernate Session interface used to create a Criteria object that yields instances of the persistent object's class.

Creating a Criteria Instances

The org.hibernate.Criteria symbolize a query against a specific persistent class. A factory for creating Criteria instances is the Session.

Criteria criteria = sess.createCriteria(Dog.class);
criteria.setMaxResults(30);
List dogs = criteria.list();

Narrowing the result set with the Criteria

The add() method add the restriction for a criteria query.

Criteria dogs = sess.createCriteria(Dog.class);
dogs.add( Restrictions.like("name", "Tommy%") );
dogs.add( Restrictions.between("weight", minWeight, maxWeight) );
List result = dogs.list();
 
// Restrictions can be classified logically using hibernate criteria basic query.

Criteria dogs = sess.createCriteria(Dog.class);
dogs.add( Restrictions.like("name", "Tommy%") );
dogs.add( Restrictions.or( Restrictions.eq( "age", new Integer(0) ),
        Restrictions.isNull("age") ) );
List result = dogs.list();

Sorting the result set with Criteria

The org.hibernate.criterion.Order in the Criteria API uses the Organize class to order your result set by one of the properties of your object, either in ascending or descending order.
 

Criteria dogs= sess.createCriteria(Dog.class);
dogs.add( Restrictions.like("name", "T%");
dogs.addOrder( Order.asc("name") );
dogs.addOrder( Order.desc("age") );
dogs.setMaxResults(30);
List result = dogs.list();

Associations with Criteria

Restrictions can be imposed on entities that are associated by browsing associations using createCriteria():
 

Criteria dogs = sess.createCriteria(Dog.class);
dogs.add( Restrictions.like("name", "T%") );
dogs.createCriteria("puppy");
dogs.add( Restrictions.like("name", "T%") );
List result = dogs.list();

Projections, aggregation, and grouping

The org.hibernate.criterion.Projections provides a factory for Projection instances.  A projection can be applied by executing setProjection() on a query.

Example 1:
 

Criteria dogs = session.createCriteria(Dog.class);
dogs.setProjection( Projections.rowCount() );
dogs.add( Restrictions.eq("color", Color.WHITE) );
List result = dogs.list();

 

Example 2:
 

Criteria dogs = session.createCriteria(Dog.class);
dogs.setProjection( Projections.rowCount() );
dogs.setProjection( Projections.avg("weight") );
dogs.setProjection( Projections.max("weight") );
dogs.setProjection(Projections.groupProperty("color") );
List result = dogs.list()

Pagination using criteria

 The Criteria interface offers two options for pagination.

1. public Criteria setFirstResult(int fr): This method accepts an integer that represents row 0, which is the first row in the result set.

2. public Criteria setMaxResults(int mr): This function tells Hibernate how many mr objects to retrieve.

Criteria cr = session.createCriteria(Dog.class);
cr.setFirstResult(1);
cr.setMaxResults(10);
List results = cr.list();

Example Queries

With the help of the org.hibernate.criterion.Example class, you can create a hibernate criteria basic query from an existing instance.

Example example = Example.create(dog);
example.excludeZeroes();        // exclude properties with zero values
example.excludeProperty("color"); // exclude the attribute "colour"
example.ignoreCase()  ;            //compare strings without taking case into account
example.enableLike();             //use like for comparing string

List results = session.createCriteria(Dog.class);
results.add(example);
List re = results.list();

Detached queries and subqueries

With the help of the DetachedCriteria class in hibernate criteria basic query, you can construct a query outside the confines of a session and then run it using any Session.
 

DetachedCriteria avgWeight = DetachedCriteria.forClass(Dog.class);
avgWeight.setProjection( Property.forName("weight").avg() );
Criteria dogs = session.createCriteria(Dog.class);
dogs.add( Property.forName("weight").gt(avgWeight) );
List result = dogs.list(); 

Frequently Asked Questions

What are the differences between Heap and Stack Memory in Java?

The stack is frequently used to track local variables and methods' execution order. On the other side, objects are stored in heap memory. After holding, they use dynamic memory allocation and deallocation.

Can you set Hibernate's Entity class as final?

The proxy pattern is used by hibernate for lazy initialization; therefore, while you can declare an entity class as final, doing so is not advised. Hibernate won't be able to create subclasses or use the proxy pattern if you declare an entity class as final, which will limit your performance options.

What is Projection in Hibernate?

The "projection" resembles picking out the specific data you require so that NHibernate only requests that specific data from the database when it creates the SQL.

What is lazy loading in hibernate?

Hibernate's lazy loading enhances performance. The child objects are loaded as needed.

Lazy loading is now enabled by default in Hibernate 3; therefore lazy="true" is not necessary. It refers to not loading the child's objects while loading the parent.

Conclusion

Congratulations on reaching the end! In this blog, we have discussed Hibernate criteria basic query to restrict, sort, associate, and group the resultant set with examples.

Hope you liked this blog of Hibernate criteria basic query; it has added some new information to your coding journey. Please look at these similar topics to learn more:  Hibernate Interview QuestionsStructured Query LanguageLearning SQLDatabase Languages, and Microservice in Java.

 

Refer to our Coding Ninjas Studio Guided Path to learn Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and even more! You can also check out the mock test series and participate in the contests hosted by Coding Ninjas Studio! 

But if you're just starting and want to learn about questions posed by tech giants like Amazon, Microsoft, Uber, and so on. In such a case, for placement preparations, you can also look at the problemsinterview experiences, and interview bundle.

Please upvote our blogs if you find them useful and exciting!

Happy Learning!

Live masterclass