Hibernate Query Language(HQL)



HQL is the hibernate’s own query language and it is used to perform bulk operations on
hibernate programs.


An object oriented form of SQL is called HQL.


Here we are going to replace table column names with POJO class variable names
and table names with POJO class names in order to get HQL commands.


Advantages Of HQL:
HQL is database independent, means if we write any program using HQL commands then our program will be able to execute with all the databases without doing any further changes to it.


HQL supports object oriented features like Inheritance, Polymorphism, Associations(Relation ships).


HQL is initially given for selecting object from database and in hibernate 3.x we can do DML operations ( insert, update…) too.


Different Ways Of Construction HQL Select
 
If we want to select a Complete Object from the database, we use POJO class reference in
place of * while constructing the query.


In this case (select a complete object from the database) we can directly start our HQL
command from, from key word.


Example:
SQL :
sql> select * from entities_data
Note: “entities_data” is the table name right....!!!


HQL :
hql> select E from Entity E
[ or ]
from Entity E
Note: hear E is the reference...!!


If we want to load the Partial Object from the database that is only selective properties
(selected columns) of an objects then we need to replace column names with POJO class variable names.


SQL :
sql> select id,name from ENTITIES_DATA
Note: id,name are the columns entities_data is the table name right..!


HQL :
hql> select E.id,E.name from ENTITIES_DATA E
[ or ]
from ENTITIES_DATA E
( we should not start using “from” key word here because
we selecting the columns hope you are getting me )
id,name ENTITIES_DATA E


Note: hear E is the reference...!!
id,name are POJO class (Entity.java) variables.


It is also possible to load or select the object from the database by passing run time values into the query, in this case we can use either ” ? ” symbol or label in an HQL command, the index number of ” ? ” will starts from zero but not one (Remember this, little important regarding
interview point of view)


Example:
SQL :
sql> select * from ENTITY where id=?
Note: ENTITY is the table name right..!


HQL :
hql> select E from Entity E where E.id=?
[ or ]
select E from Entity E where E.id =:idVal
[ or ]
from Entity E where E.id=?
[ or ]
E from Entity E where E.id =: idVal


Note: Here E is the reference...!!


Here : idVal refers that, idVal is a label(colon ‘:’ symbol represents that its the label)
we used to store some values in this (idVal) label in run time (in our class)