Hibernate Query Language (HQL)
Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn’t depends on the table of the database. Instead of table name, we use class name in HQL. So it is database independent query language.
Advantage of HQL
There are many advantages of HQL. They are as follows:
- database independent
- supports polymorphic queries
- easy to learn for Java Programmer
It is an object oriented representation of Hibernate Query. The object of Query can be obtained by calling the createQuery() method Session interface.
The query interface provides many methods. There is given commonly used methods:
- public int executeUpdate() is used to execute the update or delete query.
- public List list() returns the result of the ralation as a list.
- public Query setFirstResult(int rowno) specifies the row number from where record will be retrieved.
- public Query setMaxResult(int rowno) specifies the no. of records to be retrieved from the relation (table).
- public Query setParameter(int position, Object value) it sets the value to the JDBC style query parameter.
- public Query setParameter(String name, Object value) it sets the value to a named query parameter.
Example of HQL to get all the records
Example of HQL to get records with pagination
Example of HQL update query
Example of HQL delete query
HQL with Aggregate functions
You may call avg(), min(), max() etc. aggregate functions by HQL. Let’s see some common examples:
Example to get total salary of all the employees
Example to get maximum salary of employee
Example to get minimum salary of employee
Example to count total number of employee ID
Example to get average salary of each employees