Objective: Suppose we have a class Employee having properties eno,ename,sal,job,deptno. We want to persists this class/object to databse table employee1000.

 

Step by step we are describing how to achieve it in Hibernate.

 You can download hibernate3.6  in this link
Step1. Create your pojo(Plain Old Java Object)

As you can see the above code which is a POJO , just having some fields that maps to the column of the employee1000 table. getter/setter of each of the fields will help access to the private fields. Since we have a field id that would represent the primary key column id . We have made the class implements the Serializable interface.
Step2.Create a Mapping file
The process of specifying the bindings between an object model ( class)  and a database schema or  tells Hibernate which tables and columns to be used to load and store objects.

  1. Principal mechanism is via XML mapping files or annotation. But first  we will go  through xml mapping file.
  2. Defacto file name extension is " .hbm.xml"
  3. Best practice is is to use one file per class.

In mapping file we generally describes

  1. Entities
  2. Basic Properties
  3. Components
  4. Associations, it can be of the following four types
    1. One-To-One
    2. One-To-Many
    3. Many-To-One
    4. Many-To-Many
  5. Inheritance Mapping.

As Employee.hbm.xml is describing bellow

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.bullraider" >
    <class name="Employee" table="emp1000">
        <meta attribute="class-description"> This class contains employee details. </meta>
        <id name="empno" type="long" column="empno">
            <generator class="native"  />
        </id>
        <property name="ename" type="string" column="ename" not-null="true" />
        <property name="job" type="string" column="job" not-null="true" />
        <property name="sal" type="integer" column="sal" not-null="true" />
        <property name="deptno" type="integer" column="deptno"
            not-null="true" />
    </class>
</hibernate-mapping>

 

<class> Class element defines the class in java to be mapped to the table in database.This element includes two attributes

  1. name: Defines fully qualified class name, in our case "com.Employee".However if the package attribute is defined in the hibernate-mapping tag, then only the Class name is needed.
  2. table : Specifies the name of table in database to which mapping file will be persisted.

<Id> : Id element consists of three elements as follows and tells which field of the POJO class will be mapped to the primary key of the table. It also takes another element  named as generator.

  1. name :Specifies name of field in the POJO
  2. type : Specifies datatype of  id (here it's long)
  3. column: Specifies what is the column name that the id will be mapped to. However if the name of the field in POJO is same as the primary key name/column name, it can be ignored.


<generator>: Element  tells hibernate how to generate the primary key or id.It has just one attribute allowed i.e class

  1. class:This specifies the class is used to generate Id.

class may be Increment,Identity,Sequence,Hilo,Native etc
Native genarator picks identity,sequence or hilo , depending database
 

<property>: Element contains many attributes but we have declared only three basic attributes.

  1. name: Specifies name of property
  2. column: Specifies database column name, again If property name and column name is same, then there is no need to specifies 'column' attributes
  3. type:Specifies type of property

Step3. Creating hibernate configuration file
   Hibernate can be configured with hibernate.cfg.xml file which describes  properties such as database dialect, connection string,pool-size ,mapping files etc. These files are searched on class path.

As it is described bellow

<?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.connection.driver_class">oracle.jdbc.OracleDriver</property>
           <!--  This  specifies name of JDBC driver class name-->
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property>
            <!-- This specifies where database server located-->
<property name="hibernate.connection.username">scott</property>
<property name="connection.password">tiger</property>
       <!--      This specifies  database username and password for connection.-->
  <property name="connection.pool_size">1</property>
            <!-- This specifies the total no of connection will established for developement-->
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
      <!--  Specifies the name of dilect is used for database connection.
Dilect differs from database to databse.-->
 <property name="show_sql">true</property>
        <!-- If we want log of SQL generated by Hibernate during persisting,then we have to mention this one-->
  <property name="hbm2ddl.auto">create</property>
        <!--  For creating table-->
   <mapping resource="com/bullraider/Employee.hbm.xml"/>
         <!--  Specifies in which location mapping file presents-->

</session-factory>
</hibernate-configuration>


Step4. Creating HibernateUtil Class
   The main purpose of class is to get SessionFactory,and since it is a heavy resource,And a single instance is sufficient , it is created as Singleton file.It Represents a set of mapping files.Main purpose is to provide Session instances.

Like this

package com.bullraider.util;

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

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("SessionFactory creation failed" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Step5. Design Main Class to get Session and execute Operation (Insertion)

>Obtained from a SessionFactory instance
>It's the main  runtime interface between a Java application and Hibernate
>Responsible for storing and retrieving objects

This is the main class

package com.bullraider;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.bullraider.util.*;
public class Main {
    public static void main(String[] args) {
        Main main1=new Main();
        main1.saveEmployee("Rex", "MGR", 30000, 10);
        main1.saveEmployee("Raj", "CLERK", 10000, 30);
        main1.saveEmployee("Mike", "SALESMAN", 8000, 10);
    }
    public void saveEmployee(String ename,String job,int sal,int deptno)
    {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        Long empId = null;
        try {
            transaction = session.beginTransaction();
            Employee emp=new Employee();
            emp.setEname(ename);
            emp.setJob(job);
            emp.setSal(sal);
            emp.setDeptno(deptno);
            session.save(emp);
            transaction.commit();
            System.out.println("Records inserted sucessessfully");
        } catch (HibernateException e) {
            transaction.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return empId;
    }
}


We have created three employee object ,and used session and transaction to save or insert the employees and commit the changes.

Download this code  emp_mapping.zip