Alphalearningschool
        

<<< Prev

Next >>>

Up
HQL

HQL (Hibernate Query Language) - Hibernate Query Language is similar to Structured Query Language).But only difference is it does not depend on table of the database. It depends on class name in HQL, so it is database independent query.

Advantage of HQL:

  • Database independent.
  • Supports polymorphic queries.
  • Easy to learn for Java Programmer.

Example of HQL :

To get all the records:

Query query=session.createQuery("from Emp");//here persistent class name is Emp  
List list=query.list();

 

 To get records with pagination:

Query query=session.createQuery("from Emp");//here persistent class name is Emp  
List list=query.list();

 

Update query :

Transaction tx=session.beginTransaction();  
Query q=session.createQuery("update User set name=:n where id=:i");  
q.setParameter("n","Manish  Kumar");  
q.setParameter("i",100);  
int status=q.executeUpdate();  
System.out.println(status);  
tx.commit();  

 

Delete query :

Query query=session.createQuery("delete from Emp where id=100");  
//specifying class name (Emp) not tablename  
query.executeUpdate();

 

Aggregate functions: aggregate functions by HQL. example  avg(), min(), max() etc.

Some common examples:

To get total salary of all the employees :

Query q=session.createQuery("select sum(salary) from Emp");  
List<Integer> list=q.list();  
System.out.println(list.get(0));

 

To get maximum salary of employee :

 

Query q=session.createQuery("select max(salary) from Emp");

 

To get minimum salary of employee:

Query q=session.createQuery("select min(salary) from Emp");

 

To count total number of employee ID :

Query q=session.createQuery("select count(id) from Emp");  

 

To get average salary of each employees:

Query q=session.createQuery("select avg(salary) from Emp");