Hibernate Query Language (HQL)

HQL:

HQL stands for Hibernate Query Language. HQL syntax is quite similar to SQL syntax but it performs operations on objects and properties of persistent classes instead of tables and columns. Hibernate framework translate HQL queries into database specific queries to perform action.

Query interface provides the methods and functionality to represent and manipulate a HQL query in the object oriented way.

Note: We can directly use SQL statements in hibernate.

Example:

Student.java

/**
 * This class represents a persistent class for Student.
 * @author javawithease
 */
public class Student {
	//data members
	private int studentId;
	private String firstName;
	private String lastName;
	private String className;
	private String rollNo;
	private int age;
 
	//no-argument constructor
	public Student(){
 
	}
 
	//getter and setter methods
	public int getStudentId() {
		return studentId;
	}
	public void setStudentId(int studentId) {
		this.studentId = studentId;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public String getClassName() {
		return className;
	}
	public void setClassName(String className) {
		this.className = className;
	}
	public String getRollNo() {
		return rollNo;
	}
	public void setRollNo(String rollNo) {
		this.rollNo = rollNo;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
 
}

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 
<hibernate-configuration>
 
    <session-factory>
        <property name="dialect">
           org.hibernate.dialect.OracleDialect
        </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="connection.driver_class">
           oracle.jdbc.driver.OracleDriver
        </property>
        <property name="hbm2ddl.auto">
           update
        </property>
        <property name="show_sql">
           true
        </property>
 
        <mapping resource="student.hbm.xml"/>
 
    </session-factory>
 
</hibernate-configuration>

student.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping SYSTEM
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 
<hibernate-mapping>
 
 <class name="com.javawithease.business.Student" table="Student">
  <id name="studentId" type="int" column="Student_Id">
	<generator class="native"></generator>
  </id>
 
  <property name="firstName" column="First_Name" type="string"/>
  <property name="lastName" column="Last_Name" type="string"/>
  <property name="className" column="Class" type="string"/>
  <property name="rollNo" column="RollNo" type="string"/>
  <property name="age" column="Age" type="int"/>
 
 </class>
 
</hibernate-mapping>

HibernateUtil.java

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
/**
 * This is a utility class for getting the hibernate session object.
 * @author javawithease
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory = 
                                           buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
    	SessionFactory sessionFactory = null;
        try {
        	//Create the configuration object.
        	Configuration configuration = new Configuration(); 
        	//Initialize the configuration object 
                //with the configuration file data
        	configuration.configure("hibernate.cfg.xml");
        	// Get the SessionFactory object from configuration.
        	sessionFactory = configuration.buildSessionFactory();
        }
        catch (Exception e) {
           e.printStackTrace();
        }
        return sessionFactory;
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
}

HibernateTest.java

import org.hibernate.Query;
import org.hibernate.Session;
import com.javawithease.persistence.HibernateUtil;
 
/**
 * This class is used for the hibernate operations.
 * @author javawithease
 */
public class HibernateTest {
    public static void main(String args[]){
        //Create the student object.
        Student student = new Student();
 
        //Setting the object properties.
        student.setFirstName("Vivek");
        student.setLastName("Solenki");
        student.setClassName("MCA ");
        student.setRollNo("MCA/07/70");
        student.setAge(27);
 
        //Get the session object.
        Session session = 
                HibernateUtil.getSessionFactory().openSession();
 
        //Start hibernate transaction.
        session.beginTransaction();
 
        //Persist the student object.
        session.save(student);
 
        //Update the student object.
        Query query1 = session.createQuery("update Student" + 
                " set className = 'MCA final'" +
		" where rollNo = 'MCA/07/70'");
        query1.executeUpdate();
 
        //select a student record
        Query query2 = session.
           createQuery("FROM Student where rollNo = 'MCA/07/70'");
        Student stu1 = (Student) query2.uniqueResult();
        System.out.println("First Name: " + stu1.getFirstName()); 
        System.out.println("Last Name: " + stu1.getLastName()); 
        System.out.println("Class: " + stu1.getClassName()); 
        System.out.println("RollNo: " + stu1.getRollNo()); 
        System.out.println("Age: " + stu1.getAge()); 
 
        //select query using named parameters
        Query query3 = session.
              createQuery("FROM Student where rollNo = :rollNo");
        query3.setParameter("rollNo", "MCA/07/70");
        Student stu2 = (Student) query3.uniqueResult();
        System.out.println("First Name: " + stu2.getFirstName()); 
        System.out.println("Last Name: " + stu2.getLastName()); 
        System.out.println("Class: " + stu2.getClassName()); 
        System.out.println("RollNo: " + stu2.getRollNo()); 
        System.out.println("Age: " + stu2.getAge());
 
        //select query using positional parameters
        Query query4 = session.
                    createQuery("FROM Student where rollNo = ?");
        query4.setString(0, "MCA/07/70");
        Student stu3 = (Student) query4.uniqueResult();
        System.out.println("First Name: " + stu3.getFirstName()); 
        System.out.println("Last Name: " + stu3.getLastName()); 
        System.out.println("Class: " + stu3.getClassName()); 
        System.out.println("RollNo: " + stu3.getRollNo()); 
        System.out.println("Age: " + stu3.getAge());
 
        //delete a student record
        Query query5 = session.createQuery("delete Student" + 
                                " where rollNo = 'MCA/07/70'");
        query5.executeUpdate();
 
        //Commit hibernate transaction.
        session.getTransaction().commit();
 
        //Close the hibernate session.
        session.close();
      }
}

Output:

Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into Student (First_Name, Last_Name, 
Class, RollNo, Age, Student_Id) values (?, ?, ?, ?, ?, ?)
Hibernate: update Student set Class='MCA final' where 
RollNo='MCA/07/70'
Hibernate: select student0_.Student_Id as Student1_0_, 
student0_.First_Name as First2_0_, student0_.Last_Name 
as Last3_0_, student0_.Class as Class0_, student0_.RollNo 
as RollNo0_, student0_.Age as Age0_ from Student 
student0_ where student0_.RollNo='MCA/07/70'
First Name: Vivek
Last Name: Solenki
Class: MCA 
RollNo: MCA/07/70
Age: 27
Hibernate: select student0_.Student_Id as Student1_0_, 
student0_.First_Name as First2_0_, student0_.Last_Name 
as Last3_0_, student0_.Class as Class0_, student0_.RollNo 
as RollNo0_, student0_.Age as Age0_ from Student 
student0_ where student0_.RollNo=?
First Name: Vivek
Last Name: Solenki
Class: MCA 
RollNo: MCA/07/70
Age: 27
Hibernate: select student0_.Student_Id 
as Student1_0_, student0_.First_Name as First2_0_, 
student0_.Last_Name as Last3_0_, student0_.Class 
as Class0_, student0_.RollNo as RollNo0_, student0_.Age
 as Age0_ from Student student0_ where student0_.RollNo=?
First Name: Vivek
Last Name: Solenki
Class: MCA 
RollNo: MCA/07/70
Age: 27
Hibernate: delete from Student where RollNo='MCA/07/70'

Download this example.
 
Next Topic: Hibernate Criteria Query Language (HCQL) with example.
Previous Topic: Hibernate component mapping with example.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.