Hibernate Query Language(HQL) Select query

To start with we create a class Student, with properties id, marks, name and extraSubject. We also generate necessary getters and setters. We create a hibernate mapping file to map this class to database tables and a hibernate configuration file to set up our environment to use hibernate. For a quick reference reader can see all above classes and configuration files here

In HQL, to select all instances of a particular class, we do not need to write SELECT keyword. We can just use keyword FROM followed by name of class as:

from Student

The above query retrieves all persistent instances of Student from database.

we can also create alias of queried class to use it in other parts of query as:

from Student as student

the above query creates a alias of class Student as student. We assign alias to the instances of queried class to refer to their property values in later part of the query. This will be more clear as we proceed furthur in this tutorial.

we can drop even “as” keyword in above query and write

from Student student

To understand this further, lets save some instances and retrieve them using HQL. The code for the program is given below:

package com.thecafetechno.main;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.thecafetechno.university.Student;
import com.thecafetechno.util.HibernateUtil;

public class DataSelectionHQLExample {
	public static void main(String[] ar) {
		Student firstStudent = new Student();
		firstStudent.setName("Saurabh");
		firstStudent.setMarks(83);
		firstStudent.setExtraSubject("Computing");

		Student secondStudent = new Student();
		secondStudent.setName("Pushpi");
		secondStudent.setMarks(75);
		secondStudent.setExtraSubject("Simulation");

		Student thirdStudent = new Student();
		thirdStudent.setName("Pooja");
		thirdStudent.setMarks(78);
		thirdStudent.setExtraSubject("routing algorithms");

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction transaction = session.beginTransaction();
		session.save(firstStudent);
		session.save(secondStudent);
		session.save(thirdStudent);

		session = HibernateUtil.getSessionFactory().openSession();
		transaction = session.beginTransaction();
		// .list() method executes the Query instance
		List<Student> studentList = session.createQuery("from Student").list();
		transaction.commit();
		for (Student student : studentList) {
			System.out.println(student);
		}
	}
}

The above code first saves few instances of Student and then retrieves them using HQL query.

session.createQuery("from Student")

This line create a new query instance using createQuery() method for our HQL query passed as an argument to it.

session.createQuery("from Student").list();

The query is executed using list() method which returns result as List of Objects.