Searching...
Sunday, 18 August 2013

Hibernate Native SQL

08:54

Hibernate supports native SQL queries as well, in the below code snippet we will see how to use Native SQL in hibernate. Since Hibernate 3.x offers you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

Session objects createSQLQuery(“Query”) method is using to get SQLQuery object. We can make use of this either as Scalar query or entity query. 

SQLQuery query = session.createSQLQuery("select * from student")
                .addEntity(Student.class);
        List list = query.list();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            Student stud = (Student) it.next();
            System.out.println(stud.getName());
            System.out.println(stud.getStandard());
        }
 
        System.out.println("Executing Select Scalar Query");
 
        SQLQuery query1 = session.createSQLQuery("select name,standard from student");
        query1.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
        List list1 = query1.list();
 
        for (Object object : list1) {
            Map row = (Map) object;
            System.out.println("name: " + row.get("name"));
            System.out.println("standard:" + row.get("standard"));
        }
 

Reference

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html

0 comments: