Hibernate Query Language
I always try to write things in such a manner that everyone will be able to read and learn things in one sitting. This article will cover the Hibernate query language from start to finish. In this blog, we will be discussing what HQL is, how it works, and some practical examples.
HQL is similar to SQL query based or OOPs as query depends on object.
HQL query internally translated by Hibernate into SQL query to performs insert, update, delete and other database operations.
HQL keywords are not case sensitive such as FROM, SELECT, INSERT, DELECT, etc.
FROM
From keyword helps us to read data from specific class. It returns list of objects.
OUTPUT:
John
SELECT
SELECT keyword also helps us to read data from specific table using class name.
SELECT keyword allows us to fetch mentioned column in query. It returns list of objects.
OUTPUT:
John
WHERE
WHERE keyword we can us to refine or filter record.
OUTPUT:
John
ORDER BY
ORDER BY keyword helps us to order records in defined order.
OUTPUT:
Johnnn = 30
Singh = 31
Tarun = 31
Prachi = 31
Nitin = 32
Mengji = 35
GROUP BY
GROUP BY will return unique records for particular condition.
Below example will return unique users of every age. It will return user which exist on first position in table.
OUTPUT:
Johnnn = 30
Singh = 31
Mengji = 35
Nitin = 32
UPDATE
UPDATE keyword helps us to update record using executeUpdate() method. executeUpdate() method return 1 on successful update and 0 on failure.
DELETE
DELETE query will helps us to delete record from table. Below example will delete user having userId 1.
INSERT
INSERT query will helps us to insert record into database.
Aggregate Methods
Please find below some example related to aggregate methods.
We will be using below table as reference to work on aggregate method examples.
query.uniqueResult() will return the Double, Long and int as a query result or output.
avg(): Get average of given input criteria output.
OUTPUT:
Average = 31.5
count(): Get count of given input criteria output.
OUTPUT:
Count = 6
max(): Get maximum value of given input criteria output.
OUTPUT:
Max = 35
min(): Get minimum value of given input criteria output.
OUTPUT:
Min = 30
sum(): Get sum of given input criteria output.
OUTPUT:
Sum = 189
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.