Wednesday, June 4, 2014

Hibernate Session createQuery() vs createSQLSquery() vs get()

What are the difference between createQuery, createSQLSquery method of class Hibernate's Session class?


createQuery - uses HQL like "FROM Student" where "Student" is the mapping object class name.
Eg:       
        Session session = factory.openSession();
        Query query = session.createQuery("FROM Student where studentId="
                + studentId);
        Student ss = (Student) query.list().get(0);
        System.out.println(ss.getFirstName() + "    " + ss.getLastName());
        session.close();


createSQLQuery -uses native SQL like "select * from student" where student is the table name.
Eg:
        Session session = factory.openSession();
        SQLQuery query = session.createSQLQuery("select * from student where student_id="
                        + studentId);
        query.addEntity(Student.class);
        List list = query.list();
        for (Object object : list) {
            System.out.print(((Student) object).getFirstName()+"     "+((Student) object).getLastName());
        }   
        session.close();

You need to mention the entity class for which class you are looking for.

get  - returns the persistent instance of the given entity class with the given identifier (mentioned in mapping Student.hbm.xml as id (student_id column)).
Eg:
        Session session = factory.openSession();
        Student ss = (Student) session.get(Student.class,student_id);
        System.out.println(ss.getFirstName() + "    " + ss.getLastName());
        session.close();

No comments: