Working Example of Hibernate with explanation


A Hibernate has mainly three components:
1. Hibernate Mapping File (*.hbm.xml)
2. Hibernate Configuration File (*.cfg.xml)
3. Persistence  Object (*.class)

Mapping File: Mapping  the Contact Object to the Database Contact table
The file contact.hbm.xml is used to map Contact Object to the Contact table in the database. 
Here is the code for contact.hbm.xml:

contact table must has ID, firstname, lastname, email field as describe in mapping file

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jan 1, 2002 12:34:16 AM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
    <class name="hibernateappexample.Contact" table="contact" catalog="stu">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <property name="firstname" type="string">
            <column name="FIRSTNAME" length="25" />
        </property>
        <property name="lastname" type="string">
            <column name="LASTNAME" length="25" />
        </property>
        <property name="email" type="string">
            <column name="EMAIL" length="25" />
        </property>
    </class>
</hibernate-mapping>

Hibernate Configuration file is simple xml documents. In this application Hibernate provided connection pooling and transaction management is used for simplicity. Hibernate uses the hibernate.cfg.xml to create the connection pool and setup required environment. 
Here is the code: 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/stu</property>
    <property name="hibernate.connection.username">root</property>
    <mapping resource="hibernateappexample/Contact.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Persistence Class

Hibernate 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 Contact.java: 

package hibernateappexample;

public class Contact {
  private String firstName;
  private String lastName;
  private String email;
  private long id;

  /**
   * @return Email
   */
  public String getEmail() {
    return email;
  }

  /**
   * @return First Name
   */
  public String getFirstName() {
    return firstName;
  }

  /** 
   * @return Last name
   */
  public String getLastName() {
    return lastName;
  }

  /**
   * @param string Sets the Email
   */
  public void setEmail(String string) {
    email = string;
  }

  /**
   * @param string Sets the First Name
   */
  public void setFirstName(String string) {
    firstName = string;
  }

  /**
   * @param string sets the Last Name
   */
  public void setLastName(String string) {
    lastName = string;
  }

  /**
   * @return ID Returns ID
   */
  public long getId() {
    return id;
  }

  /**
   * @param l Sets the ID
   */
  public void setId(long l) {
    id = l;
  }

Setting Up MySQL Database
In the configuration file(contact.cfg.xml) we have specified to use stu database running on localhost.  So, create the databse ("stu") on the MySQL server running on localhost.

Developing Code to Test Hibernate example

Now we are ready to write a program to insert the data into database. We should first understand about the Hibernate's Session. Hibernate Session is the main runtime interface between a Java application and Hibernate. First we are required to get the Hibernate Session.SessionFactory allows application to create the Hibernate Sesssion by reading the configuration from hibernate.cfg.xml file.  Then the save method on session object is used to save the contact information to the database:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hibernateappexample;

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

/**
 *
 * @author navindra
 */
public class Main {

    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
    Session session=null;
    Contact contact=null;
    Transaction tx=null;
    SessionFactory factory=null;
    try{
    Configuration cfg=new Configuration().configure("contact.cfg.xml");
    factory=cfg.buildSessionFactory();
    session= factory.openSession();
    tx=session.beginTransaction();
    contact=new Contact();
    contact.setId(3);
    contact.setFirstname("Naveen");
    contact.setLastname("Jha");
    contact.setEmail("jha@gmail.com");
    session.save(contact);
    tx.commit();
    }catch(Exception e){
        System.out.print("Error"+e);
    if(tx!=null){
        try{
            tx.rollback();
        }catch(Exception e1){
        System.out.print("Error"+e1);
        }
    }

    }
  finally{
  if(session!=null){
      try{
          session.flush();
          session.close();
      }
      catch(Exception e2){
      System.out.print("Error"+e2);
      }
  }
  }
    
    }

}

No comments:

Post a Comment