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 – 

package hql1;

import javax.persistence.*;

@Entity
public class Book {
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private int bookId;
	
	@Column(name = "book_name")
	private String bookName;


	public int getBookId() {
		return bookId;
	}

	public void setBookId(int bookId) {
		this.bookId = bookId;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	
}

HibernateHqlExample.java – 


package hql1;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

import java.util.*;

public class HibernateExample1 {
	
	public static void main(String[] args) {
		
		SessionFactory factory = null;
		
		Session session = null;
		
		Configuration configuration = new Configuration().configure();
		
		try {
			
			factory = configuration.buildSessionFactory();
			
			session = factory.openSession();
			
			Transaction tx = session.beginTransaction();
			//HQL hibernate query language. mainly used to fetch the data from database.
			Query query = session.createQuery("from Book");
			
			List<Book> bookList = query.list();
			
			System.out.println("size of list--  "+bookList.size());
			
			for(Book bl: bookList) {
				
				System.out.println("book id is "+bl.getBookId());
				
				System.out.println("book name is  "+bl.getBookName());
			}
			
			tx.commit();
			
			System.out.println("Hql example to fetch the record");
		} catch (Exception e) {
			
			e.printStackTrace();
			

		} finally {

			session.close();
			
			factory.close();
		}
	}
}

hibernate.cfg.xml – 

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">SYSTEM</property>
<property name="connection.password">oracle</property>
 
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
 <mapping class="hql1.Book" />

 
</session-factory>
</hibernate-configuration>

When you run this program expected output is – 

Explanation – Let’s see what is happening here.

Query query = session.createQuery("from Book");
			
			List<Book> bookList = query.list();
			
			System.out.println("size of list--  "+bookList.size());
			
			for(Book bl: bookList) {
				
				System.out.println("book id is "+bl.getBookId());
				
				System.out.println("book name is  "+bl.getBookName());
			}
  1. we are getting Query interface reference with help of  Session’s createQuery(“”) method.
  2. Query query = session.createQuery("from Book");
  3. Query interface has list() method which returns list of entity.
  4. List<Book> bookList = query.list();
  5. Rest of is basic java programming.