Hibernate Criteria Query

Hibernate 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

Specialist Master (Architect) with a passion for cutting-edge technologies like AEM (Adobe Experience Manager) and a proven track record of delivering high-quality software solutions.

  • Languages: Java, Python
  • Frameworks: J2EE, Spring, Struts 2.0, Hibernate
  • Web Technologies: React, HTML, CSS
  • Analytics: Adobe Analytics
  • Tools & Technologies: IntelliJ, JIRA

🌐 LinkedIn

πŸ“ Blogs

πŸ“§ Imran Khan