Hibernate Native SQL Query | Hibernate 4 Native SQL Example

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we are going to learn about Hibernate Native SQL with example. Hibernate gives a facility to execute SQL commands directly on the database with a technique called native SQL.
To execute SQL commands from hibernate, Hibernate given us SQLQuery. SQLQuery is an interface which is coming from the org.hibernate package.
We can obtain the SQLQuery instance by calling the createSQLQuery() on hibernate session like below :
String qry = "select * from student";
SQLQuery sqlQuery = session.createSQLQuery(qry);
In the above example, we try to select the entire row with the SQL command. In this case, Hibernate converts each row into Object[] but not into Object of POJO class.
If we want to tell the Hibernate, that convert each row into an object of POJO class, we need to call addEntity() method of SQLQuery object. That Query object is called an EntityQuery.
String qry = "select * from student";
SQLQuery sqlQuery = session.createSQLQuery(qry);

sqlQuery.addEntity(Student.class);

List list = sqlQuery.list();
In the above example, now the list contains Student class objects. So that we can directly cast into Student type :
Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            Student student = (Student) iterator.next();
            System.out.println("sId : " + student.getStudentId() + " sName : "
                    + student.getStudentName() + " age : " + student.getAge());
While reading partial row with native SQL query, to find the column types, hibernate internally uses ResultSetMetaData. If we want to tell to hibernate explicitly about the columns, which we want to select, then we can call addScalar() on SQLQuery object like below :
String qry = "select * from student";
SQLQuery sqlQuery = session.createSQLQuery(qry);

sqlQuery.addScalar("sid", IntegerType.INSTANCE);
sqlQuery.addScalar("sname", StringType.INSTANCE);

List list = sqlQuery.list();
In the above example, we pass the two parameters to addScalar() method1 is for the column name, and 2nd is the type of column. In this case, the list contains Object[], since it is a partial entity. Why?
Likewise, we can do even non-select operations like insert, update and delete with Hibernate Native SQL query. Here is the complete example :
Creating Student Pojo
Student.java
package com.otp.hibernate.pojo;

public class Student {
    private int studentId;
    private String studentName;
    private String address;
    private int age;

    public int getStudentId() {
        return studentId;
    }

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Hibernate Mapping class :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.otp.hibernate.pojo.Student" table="student"
        schema="onlinetutorialspoint">
        <id name="studentId" column="sid">
            <generator class="increment" />
        </id>
        <property name="studentName" column="sname" />
        <property name="address" column="address" />
        <property name="age" column="age" />
    </class>
</hibernate-mapping>
Main.java
import java.util.Iterator;
import java.util.List;

import org.hibernate.Filter;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;

import com.otp.hibernate.pojo.Student;

public class Main {

    public static void main(String[] args) {
        Configuration configuration = new Configuration()
                .configure("hibernate.cfg.xml");
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties());
        SessionFactory factory = configuration.buildSessionFactory(builder
                .build());

        Session session = factory.openSession();
        String qry = "select * from student";
        SQLQuery sqlQuery = session.createSQLQuery(qry);

        List list = sqlQuery.list();

        Iterator iterator = list.iterator();

        while (iterator.hasNext()) {
            Object[] object = (Object[]) iterator.next();
            System.out.println("sId : " + object[0] + " sName : " + object[1]
                    + " age : " + object[2]);
        }

        // addEntity
        System.out.println("***********Entity*************");
        String qry2 = "select * from student";
        SQLQuery sqlQuery2 = session.createSQLQuery(qry2);
        sqlQuery2.addEntity(Student.class);

        List list2 = sqlQuery2.list();
        Iterator iterator2 = list2.iterator();

        while (iterator2.hasNext()) {
            Student student = (Student) iterator2.next();
            System.out.println("sId : " + student.getStudentId() + " sName : "
                    + student.getStudentName() + " age : " + student.getAge());
        }

        // addSclar
        System.out.println("***********SCALAR*************");

        String qry3 = "select * from student";
        SQLQuery sqlQuery3 = session.createSQLQuery(qry3);

        sqlQuery3.addScalar("sid", IntegerType.INSTANCE);
        sqlQuery3.addScalar("sname", StringType.INSTANCE);

        List list3 = sqlQuery3.list();
        Iterator iterator3 = list3.iterator();

        while (iterator3.hasNext()) {
            Object[] object = (Object[]) iterator3.next();
            System.out.println("sId : " + object[0] + " sName : " + object[1]);
        }

        // update
        System.out.println("**********Update**********");

        Transaction transaction = session.beginTransaction();
        String qry4 = "update student set age=:age where sid=:id";
        SQLQuery sqlQuery4 = session.createSQLQuery(qry4);
        sqlQuery4.setParameter("id", 2);
        sqlQuery4.setParameter("age", 30);
        sqlQuery4.executeUpdate();

        transaction.commit();
        System.out.println("Completed");
        session.clear();
        session.close();
    }
}
Output:
sId : 1 sName : vizag age : 20
sId : 2 sName : vizag age : 40
sId : 3 sName : hyderabad age : 30
***********Entity*************
sId : 1 sName : chandra age : 20
sId : 2 sName : shekhar age : 40
sId : 3 sName : rahul age : 30
***********SCALAR*************
sId : 1 sName : chandra
sId : 2 sName : shekhar
sId : 3 sName : rahul
**********Update**********
Completed
Though we have a facility to execute SQL commands in hibernate app, it is not recommended because it kills one of the main advantages of hibernate, That is our application becomes database dependent.
The complete example is available for download, have a look.
Happy Learning 🙂


Hibernate-NativeSQL-Example

File size: 13 KB
Downloads: 805


Hibernate Filter Example Xml Configuration
Hibernate Projection with Example
Hibernate Criteria API with Example
Hibernate Restrictions with Example
Hibernate cache first level example
Basic Hibernate Example with XML Configuration
Hibernate Left Join Example
Hibernate Composite Key Mapping Example
Difference between update vs merge in Hibernate example
hibernate update query example
Hibernate Named Query with Example
Hibernate Query Language (HQL) Select Operation
Hibernate groupby criteria HQL query Example
HQL update, delete Query Example
What is Hibernate

Hibernate Filter Example Xml Configuration
Hibernate Projection with Example
Hibernate Criteria API with Example
Hibernate Restrictions with Example
Hibernate cache first level example
Basic Hibernate Example with XML Configuration
Hibernate Left Join Example
Hibernate Composite Key Mapping Example
Difference between update vs merge in Hibernate example
hibernate update query example
Hibernate Named Query with Example
Hibernate Query Language (HQL) Select Operation
Hibernate groupby criteria HQL query Example
HQL update, delete Query Example
What is Hibernate






arun singh
May 4, 2019 at 12:02 am - Reply 

explained addEntity and addScalar well. Thanks










arun singh
May 4, 2019 at 12:02 am - Reply 

explained addEntity and addScalar well. Thanks




explained addEntity and addScalar well. Thanks
 


Δ
 Hibernate – Introduction
 Hibernate – Advantages
 Hibernate – Download and Setup
 Hibernate – Sql Dialect list
 Hibernate – Helloworld – XML
 Hibernate – Install Tools in Eclipse
 Hibernate – Object States
 Hibernate – Helloworld – Annotations
 Hibernate – One to One Mapping – XML
 Hibernate – One to One Mapping foreign key – XML
 Hibernate – One To Many -XML
 Hibernate – One To Many – Annotations
 Hibernate – Many to Many Mapping – XML
 Hibernate – Many to One – XML
 Hibernate – Composite Key Mapping
 Hibernate – Named Query
 Hibernate – Native SQL Query
 Hibernate – load() vs get()
 Hibernate Criteria API with Example
 Hibernate – Restrictions
 Hibernate – Projection
 Hibernate – Query Language (HQL)
 Hibernate – Groupby Criteria HQL
 Hibernate – Orderby Criteria
 Hibernate – HQLSelect Operation
 Hibernate – HQL Update, Delete
 Hibernate – Update Query
 Hibernate – Update vs Merge
 Hibernate – Right Join
 Hibernate – Left Join
 Hibernate – Pagination
 Hibernate – Generator Classes
 Hibernate – Custom Generator
 Hibernate – Inheritance Mappings
 Hibernate – Table per Class
 Hibernate – Table per Sub Class
 Hibernate – Table per Concrete Class
 Hibernate – Table per Class  Annotations
 Hibernate – Stored Procedures
 Hibernate – @Formula Annotation
 Hibernate – Singleton SessionFactory
 Hibernate – Interceptor
 hbm2ddl.auto Example in Hibernate XML Config
 Hibernate – First Level Cache