Sunday, July 27, 2014

Hibernate Basic Tutorial

Please read a discussion on ORM, before going further at ORM Introduction
Hibernate is an ORM framework. It provides capability to interact with database in an object oriented way. Hibernate provides its own HQL (Hibernate query language) also. The concepts of ORM are now adopted in EJB3.0 in the form of entity beans and Jave Persistence API (JPA). Hibernate supports Entity beans also. This means hibernate can act as an implementation provider for Entity beans. In fact, JBoss uses hibernate as implementation provider for Entity beans. Hibernate has its own set of API's also which at the moment are richer than JPA. Going forward however we might see Entity beans and JPA closing this gap.
Hibernate is a Object relational mapping framework. What it will help us is in saving the objects into the relational world. So let's have our Java class whose object instances at runtime will be saved by hibernate to the database.
public class Student {


    //Id will correspond the primary key in the database

    private Long id;

    protected String name;


    public Long getId() { return id; }

    public void setId(Long id) { = id;}
    public String getName() {return name;}
    public void setName(String name) { = name;}

Now we have the domain class definition with us. Now we will put a mapping file which will map this class to the data model in the database. We are not creating the table in the database as we will use hibernate to generate the data model. Though in real life application you would have your data model already created and placed in the database.
Student.hbm.xml (Put it together with Student class)

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"


  <!-- class attributes - 

        name - Java class name

        table - Table to which this class is mapped

        schema - The schema where it sits

    id -

        name - name of property on Java class. It will result in getId() and setId method

        column - column in table to which it is mapped
        generator- how the id's to be generated
    <class name="com.oyejava.Student" table="Student" schema="PUBLIC">
        <id name="id" column="STUDENT_ID">
            <generator class="increment"/>
        <!-- name - name of property in Java class. getName() and setName()
             column - column in table to which it is mapped.  -->
        <property name="name" column="NAME" />

Now we will provide hibernate the details to connect to the database. Similar to JDBC coding, the connection details and drivers need to be provided to Hibernate. We will use hsql, the details of which can be seen at Hypersonic. This is done in a XML file.
hibernate.cfg.xml (Put it in the class path)

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"



       <!-- Database connection settings -->

           <!--  If the below drive does not works try org.hsqldb.jdbc.JDBCDriver-->

        <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>

        <property name="connection.url">jdbc:hsqldb:hsql://localhost</property>

        <property name="connection.username">sa</property>

        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect - This tells the SQL grammer to be used -->
        <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Log out all the sql that hibernate is issuing to datbase.

             This is very useful for debugging -->

        <property name="show_sql">true</property>

        <!-- Create the table looking at class and mapping. Very useful in development

             Use validate in production environments. -->

        <property name="">create</property>

        <!-- Mapping file.  -->

        <mapping resource="com/oyejava/Student.hbm.xml"/>



Now we will write a utility class which will start the session factory of hibernate, if it is not started and will return the Session factory. This is the most used pattern of boot strapping Hibernate. Session factory contains all the configuration information at runtime. A Session is retrieve from the Session factory. A session is a light weight object which provide services to interact with database. You can think of Session like JDBC connection, thought it may not open the database connection if not required.

public class HibernateUtil {


    private static SessionFactory sessionFactory;




            //By default it will look for hibernate.cfg.xml in the class path

            sessionFactory=new Configuration().configure().buildSessionFactory();
        }catch(Throwable ex){
            throw new ExceptionInInitializerError(ex);
    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    public static void shutdown(){
        //Close caches and connection pool

Now let's write the main class in which we will create a Student object and persist it to database

public class HibernateBasic {
    public static void main(String[] args) {
        //Get the session from the Session factory

        Session session = HibernateUtil.getSessionFactory().openSession();

        Transaction tx= session.beginTransaction();        


        Student student = new Student();


        Long studentId = (Long);

Run the application and check in the database. It should persist a row of data. Download the source code from down below in the attachment section. The libraries has to be included as per the list given above.
In the above example we saw how to configure hibernate using XML mapping. The present trend is however to move towards annotation based mapping.

More write-ups on Hibernate

No comments:

Post a Comment