Different ways to create Queries in Hibernate

Posted By : Hitesh Arora | 01-Mar-2015


There are three different ways in hibernate to create query instance :

1.Using HQL syntax
2.Using SQL syntax
3.Using criteria API


To create any query we need to obtain the Session object which is used to create new database entities.

	Session session = SessionFactory.getCurrentSession();

1.  HQL syntax : HQL stands for hibernate query language which 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 a database independent query language. This HQL query returns all objects for a given class in the database.

For example :

	String hqlQuery = "from Employee";
	Query query = session.createQuery(hqlQuery);
	List employeeList = query.list();


2.  SQL syntax : When we want to execute database specific queries in hibernate use SQL syntax.

For example :

	String sqlQuery = "select emp_id,emp_name from Employee";
	SQLQuery query = session.createSQLQuery(sqlQuery);
        List employeeList = query.list();


3.  Using Criteria API: To retrieve data in hibernate, we can also make use of criteria API. It is used to fetch the records based on the specific criteria. For example: get all the employees whose salary is greater than 1000,

	Criteria criteria = session.createCriteria(Employee.class);
        List employeeList = criteria.list();



After working with all the queries, I found HQL to be suitable where we need to perform CRUD operations as it is not possible to do the same using criteria API.
For retriveing only must make use of criteria api as it provides the clear way to add restrictions to queries with java objects.





About Author

Author Image
Hitesh Arora

Hitesh is a bright engineer with experience in Core Java , Grails , Elastic Search , Angular JS .

Request for Proposal

Name is required

Comment is required

Sending message..