Constructor based HQL – Select new object in Hibernate

The Constructor based HQL shows you how to create query select new object in hibernate for improving performance. Normally, almost of developer don’t bother retrieving the whole entity with all its properties. While they don’t really need all of them in a particular case. For example, we have a single entity with 25 properties, and we just need a few to display to user. In case, if we execute the query to get thousands of records, the unused fields will make us heavily jamming and lead to a huge performance hit in our application.

Other interesting posts you may like

HQL/JPA provides us with a select new constructor call to deal with the above issue. We create a simple Constructor based HQL like below:

In fact, we often use Constructor based HQL for reporting queries, which allows the us to select aggregated values as well. To do this, we should create a bean that will store the aggregated values of query. This class is just poor java class. It is not a entity neither doesn’t put it in hibernate configuration file. The Constructor based HQL with aggregated values looks like below:

Reporting Queries just select the used fields so that it avoid the overhead of retrieved entities getting cached in the persistent context. It makes a huge improvement in the performance compared to the traditional retrieval technique with Hibernate.

Let’s create example to clarify how Constructor based HQL works.

Create project directory structure
In this Constructor based HQL tutorial, we will create the final project directory structure like below:

Constructor based HQL, Select new object in Hibernate

Create a program for testing
This program will query student data from database by using Constructor based HQL. Here we get the available student with id=33.

Run above the main like java application and produce the output like below:

As you can see the above program. It’s quite easy to create Constructor based HQL with aggregated values.

Noticed that the constructor-based HQL query will return all instances in transient state. It means that it doesn’t return persistent entity instances to the persistence context cache.

Download complete source code, please click link below

HibernateConstructorHQLExample.zip (54 downloads)

Leave a Comment

*

Please share it if you found this useful
Hide Buttons