Hibernate Query Language

  • Facebook
  • Google
  • LinkedIn
  • Twitter

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of tables it deals with classes and instead of columns it deals with properties. HQL is case-insensitive except from the java classes and properties. Keywords like SELECT, FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL. Although you can use SQL statements directly with Hibernate using Native SQL but if you want to take advantage of Hibernate`s SQL generation and caching strategies you should use HQL.

HQL`s Advantage

The following are the advantages of HQL.

  • HQL is Database independent.
  • HQL is more object oriented which makes us write more easily than SQL.
  • HQL support pagination.
  • HQL is Easy to learn for Java Programmer.

From Query Example

Query query = session.createQuery("from Student where name=:name");
query.setParameter("name", "Ajay");

Select Query Example

String hql = "SELECT S.firstName FROM Student S";
Query query = session.createQuery(hql);
List results = query.list();

Order BY Query Example

String hql = "FROM Student S WHERE S.id > 20 ORDER BY S.marks DESC";
Query query = session.createQuery(hql);
List results = query.list();

Update Query Example

Query queryupdt = session.createQuery("update Student set address =:address where name =:name");
   queryupdt.setParameter("name", "Ajay");
   queryupdt.setParameter("address", "D-10 Delhi");

Delete Query Example

Query querydel = session.createQuery("delete from Student where name = :name");
     querydel.setParameter("name", "Ajay");

Insert Query Example

Query queryins = session.createQuery("insert into Student(name, address) select name, address from StudentOld");
int result = queryins.executeUpdate();

Max Query Example

Query q = session.createQuery("select max(marks) from Student");

Min Query Example

Query q = session.createQuery("select min(marks) from Student");  

Count Query Example

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

Avg Query Example

Query q = session.createQuery("select avg(marks) from Student");  
      Advertisements