Hibernate Query Language

Q.  What is Hibernate Query language(HQL) in java?

  1. Hibernate Query Language is an object-oriented query language in which we use the class name instead of table name and attribute/property name instead of column name.
  2. Hibernate is mainly used to fetch the record from the database

Note – Before hibernating 3.0 HQL is used to fetch the record from the database only but after 3.0 we can also insert the data into the database. But still, in real time project, it is mainly used to fetch the record. For saving the data we have save() and persist() method.

3.  It is database independent language. Suppose we are using MySQL database and later we want to move to Oracle then we no need to change the query.
4.  In HQL we use createQuery() method of Session interface.

Let’s see a simple example in which we will fetch the data with help of HQL.

Step 1 – First we need to insert some record in the database so that further we can retrieve using HQL. For saving the data we can run this program first or we can create a table with the name of the book and insert one or two records.

Step 2 – Now we have some record in the database.

Step 3 – We need to write entity, main class, and hibernate.cfg.xml.

Step 4 – Create a java project(Since we are not using maven for jar/library, need to download the jar and add manually in the project)

Step 5 – Download hibernate jar and add it to project( right-click on project/properties/java build path/libraries/add external jars/ browse and add).

Step 6 – define the below classes and run the main class(Don’t forget to change the username and password in hibernate.cfg.xml for the database, that you have given during installation of Oracle in your machine ).

 

Book.java – 

HibernateHqlExample.java – 

hibernate.cfg.xml – 

When you run this program expected output is – 

Explanation – Let’s see what is happening here.

  1. we are getting Query interface reference with help of  Session’s createQuery(“”) method.
  2. Query interface has list() method which returns list of entity.
  3. Rest of is basic java programming.

 

 

 

Top