Hibernate Query language
HQL is an object oriented query
language,similar to SQL, but instead of operating on tables and columns, HQL
works with persistent objects and their properties.HQL queries are
translated by hibernate into conventional SQL queries which in turns perform
action on databases.
Note: keywords like SELECT,and WHERE are
FROM not case sensitive but properties like table and column names are case
sensitive in HQL.
if you need fully qualify a class
name in HQL , just speicfy the package and class name as follows..
String hql=”FROM org.kkm.Employee”;
Note :
FROM or from are same . you can
use any of them since SQL query is not case sensitive.
Employee is Class name not the
table name.
The current queries will select all
the rows and columns data from the table.
AS Clause
The AS clause can be used to
assign aliases to the classes in HQL queries.
Example:
Note:
Here Employee.firstName is a
property of Employee object rather than a field of Employee table.
WHERE Clause
ORDER BY Clause
GROUP BY Clause
Steps for query processing in
hibernate
Iterate():lazy loading
For HQL queries the flow of lazy loading is –
- Select id (primary key) and create proper object .
2. Placed id in object
3. Based on id table rows are added to the object
4. Repeat step(1) for next rows.
Positional parameters
To pass the values dynamically (run-time) to a query we use positional parameters. Method type is setXXX(position,data)
Example
String str=”FROM Employee E WHERE E.eid=? AND E.ename=?”;
Query query=session.createQuery(str);
query.setInteger(1,101);
query.setString(2,”abc”);
Named parameters
It reduces the complexity of positional parameters by replacing with some user defined names .In named parameters we use a method setParameter(named_parameter,value) in Query Interface.
Example
String str=”FROM Employee E WHERE E.eid=:x1 AND E.ename=:x2”;
Query query=session.createQuery(str);
query.setParameter(“x1”,101);
query.setParameter(“x2”,”abc”);
Here, x1 and x2 are the named parameters used in place of positional parameter along with ‘:’ to pass the values dynamically.
When to used Positional parameters and Named parameters.
It is better to use Named parameters instead of Positional Parameters, since when we have large no of columns it will easy to know their positions by their names.