Hibernate Criteria Query

Criteria Query allows to fetch filtered records from database.

Criteria uses createCriteria() method from Session interface to create a Criteria query.

Below is the criteria query example to fetch records from database table mapped with User bean class.

User Restrictions class from org.hibernate.criterion package to create a filter. Records with get return from database depending upon the Restrictions.

Below Restrictions highlighted red in color with return records having age is equal to 31.

Let’s check some of the examples to see how Criteria Query works.

We are going to use below dataset for the for all the examples.

Below example will return all Users having age 31.

OUTPUT:
Tarun
Prachi

We can apply multiple Criteria also to fetch records.

The example criteria below will return user records where the first name begins with “T,” the age is not null and greater than 31.

OUTPUT:
Tarun

Below is the example of various criteria queries which can be use to obtain records.

Criteria Order

This is to set the order of fetched records in ascending or descending order based on field.

Order can also be set for fetched records using the addOrder() function from the Criteria interface.

org.hibernate.criterion.Order provides options to sort records either in ascending or descending order.

OUTPUT:
Tarun = 31
Prachi = 31
Nitin = 32
Mengji = 35

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0