CreateQuery Hibernate

In this section you will learn how to use CreateQuery() method in Hibernate

CreateQuery Hibernate

CreateQuery Hibernate

In this section you will learn how to use CreateQuery() method in Hibernate

Hibernate CreateQuery() :

By using CreateQuery() method you can call Hibernate Query Language (HQL).For CreateQuery() import org.hibernate.Query.
Hibernate provides minimal object oriented Query language that is HQL.It is similar to SQL.
You can write your query in HQL and call it by using CreateQuery().This is done through current session.

String hql = "FROM Student stud WHERE stud.roll > 4";
Query query = session.createQuery(hql);

Example : In this example we are selecting record of such student whose roll no is grater than 4.Student is our persistence class for table student.Here is main class code -

package net.roseindia.main;

import net.roseindia.table.Student;
import net.roseindia.util.HibernateUtil;
import java.util.*;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

public class MainClazz {

public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
String hql = "FROM Student stud WHERE stud.roll > 4";
Query query = session.createQuery(hql);
List list = query.list();
Iterator iterator = list.iterator();
System.out.println("RollNo.\tName\tCourse");
while (iterator.hasNext()) {
Student student = (Student) iterator.next();
System.out.print(student.getRoll());
System.out.print("\t"+student.getName());
System.out.println("\t"+student.getCourse());
}
session.flush();
} catch (HibernateException e) {

e.printStackTrace();
} finally {
session.close();
}
}
}

Output :

Hibernate: select student0_.roll_no as roll1_0_, student0_.course as course0_, student0_.name as name0_ from student student0_ where student0_.roll_no>4
RollNo.   Name     Course
5         Jacqub   Hibernate
6         Mandy    C
8         John     Hibernate
9         Linda    Hibernate

Click here to download complete source code