HIBERNATE HQL
HQL
HQL or Hibernate Query Language is the object-oriented query language of Hibernate
Framework.
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.
Hibernate converts HQL queries into SQL queries, which are then used to perform
database actions.
HQL has many benefits. Some benefits are – they are database independent, polymorphic
queries supported, and easy to learn for Java programmers
The Query interface provides object-oriented methods and capabilities for representing
and manipulating HQL queries
HQL Clauses
HQL is case-insensitive except for java class and variable names. So SeLeCT is the same as
sELEct is the same as SELECT, but com.brainpower.model.Employee is not same as
com.brainpower.model.EMPLOYEE
Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like
table and column names are case sensitive in HQL
1. HQL From:
HQL From is same as select clause in SQL, from Employee is same as select * from
Employee. We can also create alias such as from Employee emp or from Employee as
emp.
2. HQL Join :
HQL supports inner join, left outer join, right outer join and full join.
For example, select e.name, a.city from Employee e INNER JOIN e.address a.
In this query, Employee class should have a variable named address.
3. Aggregate Functions:
HQL supports commonly used aggregate functions such as count(*), count(distinct x),
min(), max(), avg() and sum().
4. Expressions:
HQL supports arithmetic expressions (+, -, *, /), binary comparison operators (=, >=,
<=, <>, !=, like), logical operations (and, or, not) etc.
5. HQL also supports order by and group by clauses.
6. HQL also supports sub-queries just like SQL queries.
7. HQL supports DDL, DML and executing store procedures too.
1. FROM Clause
FROM clause if you want to load a complete persistent objects into memory
Syntax:
String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();
With fully qualify a class name in HQL
Syntax:
String hql = "FROM com.brainpower.pojo.Employee";
Query query = session.createQuery(hql);
List results = query.list();
2. AS Clause
Used to assign aliases to the classes in your HQL queries
AS keyword is optional and you can also specify the alias directly after the
class name
Syntax:
String hql = "FROM Employee AS E";
Query query = session.createQuery(hql);
List results = query.list();
3. SELECT Clause
The SELECT clause is used when only a few attributes of an object are
required rather than the entire object.
Syntax:
String hql = "SELECT E.firstName FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();
4. WHERE Clause
Filtering records is done with the WHERE clause. It’s used to retrieve only
the records that meet a set of criteria.
Syntax:
String hql = "FROM Employee E WHERE E.id = 10";
Query query = session.createQuery(hql);
List results = query.list();
5. ORDER BY Clause
To sort your HQL query's results, you will need to use the ORDER BY clause. You
can order the results by any property on the objects in the result set either ascending
(ASC) or descending (DESC)
Syntax:
String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();
String hql = "FROM Employee E WHERE E.id > 10 " +
"ORDER BY E.firstName DESC, E.salary DESC ";
Query query = session.createQuery(hql);
List results = query.list();
6. GROUP BY Clause
This clause lets Hibernate pull information from the database and group it based on a
value of an attribute and, typically, use the result to include an aggregate value
Syntax:
String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " +
"GROUP BY E.firstName";
Query query = session.createQuery(hql);
List results = query.list();
7. NAMED Parameters
Hibernate supports named parameters in its HQL queries. This makes writing HQL
queries that accept input from the user easy and you do not have to defend against SQL
injection attacks.
Syntax:
String hql = "FROM Employee E WHERE E.id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();
8. UPDATE Clause
The UPDATE clause can be used to update one or more properties of an one or
more objects
Syntax:
String hql = "UPDATE Employee set salary = :salary " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
9. DELETE Clause
It is required to delete a value of an attribute
Syntax:
String hql = "DELETE FROM Employee " +
"WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
10. INSERT Clause
It is required to Insert values into the relation.
Syntax:
String hql = "INSERT INTO Employee(firstName, lastName, salary)" +
"SELECT firstName, lastName, salary FROM old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);
11. Pagination using Query
Method Action Performed
Query setMaxResults(int
Instructs Hibernate to get a specific number of items
max)
Query setFirstResult(int Takes an integer as an argument that represents the first
starting_no) row in your result set, beginning with row 0.
Syntax:
String hib = "from Student"
Query query=session.createQuery(hib);
query.setFirstResult(5);
query.setMaxResult(10);
List list=query.list();
The above example returns the record from 5 to 10.
12. Aggregate Methods
Similar to SQL, HQL has a number of aggregation techniques.
Example 1: average
String hib = "select avg(marks) from Student";
Query q=session.createQuery(hib);
Example 2: max
String hib = "select max(marks) from Student";
Query q=session.createQuery(hib);
Example 3: min
String hib = "select min(marks) from Student";
Query q=session.createQuery(hib);
Example 4: count
String hib = "select count(id) from Student";
Query q=session.createQuery(hib);
Example 5: sum
String hib = "select sum(marks) from Student";
Query q=session.createQuery(hib);
List<Integer> list=q.list();
System.out.println(list.get(0));