Home Hibernate Insert Data into Database Using Hibernate Native SQL
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Insert Data into Database Using Hibernate Native SQL

Advertisement
In this example we will show you how you can use Native SQL with hibernate. You will learn how to use Native to insert data into database. Native SQL is handwritten SQL for all database operations like insert, update, delete and select.

Insert Data into Database Using Hibernate Native SQL

     

In this example we will show you how you can use Native SQL with hibernate. You will learn how to use Native to insert data into database. Native SQL is handwritten SQL for all database operations like insert, update, delete and select. 

Hibernate provides a powerful query language Hibernate Query Language that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.


Step1: Create hibernate native sql for inserting data into database.

Hibernate Native uses only the Hibernate Core for all its functions. The code for a class that will be saved to the database is displayed below:

package hibernateexample;

import javax.transaction.*;
import org.hibernate.Transaction;
import org.hibernate.*;
import org.hibernate.criterion.*;
import org.hibernate.cfg.*;
import java.util.*;


public class HibernateNativeInsert {
  public static void main(String args[]){
  Session sess = null;
  try{
  sess = HibernateUtil.currentSession();
  Transaction tx = sess.beginTransaction();
  Studentdetail student = new Studentdetail();
  student.setStudentName("Amardeep Patel");
  student.setStudentAddress("rohini,sec-2, delhi-85");
  student.setEmail("amar@rediffmail.com");
  sess.save(student);
  System.out.println("Successfully data insert in database");
  tx.commit();
  }
  catch(Exception e){
  System.out.println(e.getMessage());
  }
  finally{
  sess.close();
  }
  }
}

 

Step 2: Create session factory 'HibernateUtil.java'.

Here is the code of session Factory:

package hibernateexample;

import java.sql.*;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.io.*;

public class HibernateUtil {
  public static final SessionFactory sessionFact;
  static {
  try {
  // Create the SessionFactory from hibernate.cfg.xml
  sessionFact = new Configuration().configure().buildSessionFactory();
  }
  catch(Throwable e) {
  System.out.println("SessionFactory creation failed." + e);
  throw new ExceptionInInitializerError(e);
  }
  }
  public static final ThreadLocal session = new ThreadLocal();
  
  public static Session currentSession() throws HibernateException {
  Session sess = (Session) session.get();
  // Open a new Session, if this thread has none yet
  if(sess == null){
  sess = sessionFact.openSession();
  // Store it in the ThreadLocal variable
  session.set(sess);
  }
  return sess;
  }
  public static void SessionClose() throws Exception {
  Session s = (Session) session.get();
  if (s != null)
  s.close();
  session.set(null); 
  }
}

 

Step 3: Hibernate native uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column. Here is the code for "Studenetdetail.java":

 

package hibernateexample;

public class Studentdetail {
  private String studentName;
  private String studentAddress;
  private String email;
  private int id;
  
  public String getStudentName(){
  return studentName;
  }
  
  public void setStudentName(String studentName){
  this.studentName = studentName;
  }
  
  public String getStudentAddress(){
  return studentAddress;
  
  }
  
  public void setStudentAddress(String studentAddress){
  this.studentAddress = studentAddress;
  }
  
  public String getEmail(){
  return email;
  }
  
  public void setEmail(String email){
  this.email = email;
  }
  
  public int getId(){
  return id;
  }
  
  public void setId(int id){
  this.id = id;
  }
}

 

Here is the output:

Download here all application.

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 29, 2008

Related Tutorials

Ask Questions?    Discuss: Insert Data into Database Using Hibernate Native SQL   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
whoisdis
June 23, 2011
can not instantiated configuration

When i am trying to write this.. sessionFact = new Configuration().configure().buildSessionFactory(); It shows a compile time error. - Cannot instantiate the type Configuration - The method configure() is undefined for the type Configuration
szyder
February 6, 2012
Wheres native

Where do you see any handwritten native sql in this example? Thumbs down.
Luis
April 5, 2012
question

And if you want to insert a value (studentName, email, etc) in a especific Row or ID of the table of Students? For example, the typical "where" Insert into STUDENTS (name,email,addres) WHERE ID = '1234'
Luis
April 5, 2012
Question Correction

Sorry i did a terrible estupid thing. I refer to update... not insert. Thanks
DMCA.com