Thursday, July 16, 2015

Hibernate setup in eclipse

So here is our first step to configure the Hibernate with our java application and create a simple program to insert some value into the database. So follow the following steps : -
TASK : - Create a basic table and insert some values in it using hibernate. Now you would be wondering from where to start so do not worry follow the steps one by one and you will be good to go…..
Step 1: – Download the following library files for hibernate

  • antlr-2.7.6.jar
  • commons-collections-3.1.jar
  • dom4j-1.6.1.jar,hibernate3.jar
  • javassist-3.4.GA.jar
  • jta-1.1.jar
  • mysql-connector-java-5.1.17-bin.jar
  • ojdbc14.jar
  • slf4j-api-1.4.2.jar
  • slf4j-simple-1.5.2.jar 

Step 2: - Goto Eclipse File -> New create new Java Project with the any name you want
Step 3: - Once you are done with creating the project on high level we will be creating the following JAVA Classes and XML files

  • hibernate.cfg.xml
  • Person.hbm.xml
  • HibernateUtil.java
  • Person.java
  • PersonDAO.java
  • TestHibernate.java (To test our application)
Step 4: - Once you are done with above setup in eclipse your project structure will look like this 

 

Step 5: - Now in our current example we are using MYSQL database as a back end so we will have following table: -

  • Schema Name :  – hibernate_example
  • Table Name : – person
  • SQL Script for Table : -

DROP TABLE IF EXISTS `hibernate_example`.`person`; CREATE TABLE  `hibernate_example`.`person` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `first_name` varchar(45) NOT NULL, `last_name` varchar(45) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
Step 6 : - hibernate.cfg.xml

 
    
             
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/hibernate_example
        root
        root      
        org.hibernate.dialect.MySQL5Dialect
         
        
        1
         
        
        thread
 
        
        true
        false
 
        
        
    
     

Step 7 : – Person.hbm.xml

    
     
        
            
        
         
        
             
        
         
    

Step 8 : – HibernateUtil.java
package com.hibernate.util;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
/**
 * Hibernate Utility used to configure Hibernate's Session Factory and retrieve
 * it.
 */
public class HibernateUtil {
 
    private static final SessionFactory sessionFactory;
 
    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            // ------ --- -------------- ---- -----------------
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            // ---- ---- --- --- --- ---------- -- -- ----- -- ---------
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    /**
     * Get the configured session factory
     * 
     * @return session factory
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
Step 9 : – Person.java
package com.hibernate.enity;
 
public class Person {
     
    private int id;
    private String firstName;
    private String lastName;
     
     
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
     
     
}
Step 10 : – PersonDAO.java
package com.hibernate.dao;
 
import org.hibernate.Session;
import org.hibernate.Transaction;
 
import com.hibernate.enity.Person;
import com.hibernate.util.HibernateUtil;
 
 
public class PersonDAO {
     
    public void saveOrUpdatePerson(Person personObj){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         
        //begin the transaction
        Transaction trans=session.beginTransaction();
         
        //Save the person in database
        session.saveOrUpdate(personObj);
         
        //Commit the transaction
        trans.commit();
    }
 
}
Step 11 : – TestHibernate.java
package com.hibernate.test;
 
import com.hibernate.dao.PersonDAO;
import com.hibernate.enity.Person;
 
public class TestHibernate {
     
    public static void main(String args[]){
         
        //1.Create the object of the Person class
        Person personObj = new Person();
         
        //2.Set the values which you want to save in the database
        personObj.setFirstName("Rahul");
        personObj.setLastName("Wagh");
         
        //3.Create the object of the DAO class which will insert our person object to TABLE
        PersonDAO personDAOObj = new PersonDAO();
        personDAOObj.saveOrUpdatePerson(personObj);
         
         
    }
}
So we good to just goto TestHibernate.java class and do Right click and select Run as Java Application. Make sure your database is running. Please post your comments and suggestions about the aritcle.

1 comment: