Monday, November 15, 2010

Hibernate Insert records into table



Problem:
               To insert data into student table in navalady database.

Solution:

Procedure:

Step 1:
            Create Hibernate Reverse Engineering wizard

Step 2:
            Create HibernateUtil.java for Creating SessionFactory.

            I have created HibernateUtil.java named as NewHibernateUtil.java.

            Include following coding into NewHibernateUtil.java

package Hiber;

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 NewHibernateUtil
{
  public static final SessionFactory sessionFact;
  static
  {
    try
    {
      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();
    if(sess == null)
    {
      sess = sessionFact.openSession();
      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:
            Create POJO class and mapping files

Step 4:

            Create jsp file named as HCQinsert.jsp

Include following coding into the HCQinsert.jsp


&lt %@page import="java.util.Date"% &gt
&lt %@page import="Hiber.Student"% &gt
&lt %@page import="org.hibernate.*" % &gt
&lt %@page import="org.hibernate.cfg.*" % &gt
&lt %@page import="Hiber.NewHibernateUtil" % &gt
&lt html &gt
    &lt head &gt
        &lt title &gt Hibernate Native SQL-Insert into table &lt /title &gt
    &lt /head &gt
    &lt body &gt
        &lt %! Session sz; % &gt
        &lt %
            try
            {
               sz=NewHibernateUtil.currentSession();
               Transaction tz=sz.beginTransaction();
              
               Student st=new Student();
               st.setStuname("Nithya");
               st.setStuno(1003);
               st.setTamil(69);
               st.setEnglish(64);
               st.setMaths(90);
               st.setScience(79);
               st.setSocialscience(87);
               Date d=new Date("1999/06/25");
               st.setJoindate(d);
               sz.save(st);

               out.println("Successfully Inserted into the Student table in Navalady Datebase");
               tz.commit();
              
            }
            catch(Exception e)
            {
                sz.close();
               
                out.println("Error Occur");
            }
          
         % &gt
    &lt /body &gt
&lt /html &gt

No comments:

Post a Comment