Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Hibernate-Native SQL


Say at times you want to write SQL queries instead of HQL or Criteria. Hibernate gives you the flexibility to write the same.


Query query = session.createSQLQuery("SELECT * FROM EMPLOYEE");
query.addEntity(Employee.class);

Inside 'createSQLQuery(...)' method we can specify the SQL query.
Then in the next line we are telling Hibernate to associate 'Employee' class with query in 'addEntity(...)' method.

Let us take the Employee class :


Employee

class Employee {

   int id;
   String name;

   -- getters and setters --
}


There should be a simple mapping file for the same :


Employee.hbm.xml

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
   <class name = "Employee" table = "EMPLOYEE">
   <id name = "id" type = "string">
     <column name = "ID">
    </id>
    <property name = "name" type = "string">
     <column name = "NAME">
    </property>
   </class>
</hibernate-mapping>


Now, let us write the main() class and save three 'Employee' objects to database.


import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSave {
   public static void main(String[] args) {

    static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();

    Query query = session.createSQLQuery("SELECT * FROM EMPLOYEE");
    query.addEntity(Employee.class);

    session.getTransaction().commit();

    session.close();
    sessionFactory.close();
  }
}

Note : You can write any SQL queries using native sql.