Criteria Query with an object property as restriction

1. Introduction

There are some scenarios where you might need to set a criteria restriction on a particular object property in a Criteria Query. In this article, we will get to know how we can do it.

2. Maven Dependency and Hibernate configuration

The pom.xml dependencies and initial Hibernate configuration of the application will be the same as we did in our previous One to many Hibernate mapping example.

3. Creating the Entity classes

Assuming that I have two entities in my application, Student and Department, such that many Students can be associated with a single Department, and vice-versa.


Explore the Student Department Hibernate association

So let’s look at creating the entity classes first.

Student.java

Department.java

4. Creating the Hibernate mapping XMLs

Student.hbm.xml

Department.hbm.xml

5. Create the Hibernate client class with the main method

Lets create the Hibernate client class with the main method, from where we will be creating the Criteria Query and will try to make a Department object property as restriction. We can do that by creating an alias for the associated Department object, same as what we have done below.

In the above snippet, we are creating a Criteria Query to retrieve all the Students in the Electronics department.

Though the query could have been simpler for the current scenario with a Named Query, but we took it other way around to understand the possible way to add criteria restriction on a particular object property.

Source code can be downloaded below.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.