Hibernate Native SQL

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

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts