Introduction to Hibernate framework

Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features.

Early in 2003, the Hibernate development team began Hibernate2 releases which offered many significant improvements over the first release.

JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers and worked with them in supporting Hibernate. Hibernate is part of JBoss (a division of Red Hat) Enterprise Middleware System (JEMS) suite of products.

1. Introduction

Hibernate is an Object-relational mapping (ORM) tool. Object-relational mapping or ORM is a programming method for mapping the objects to the relational model where entities/classes are mapped to tables, instances are mapped to rows and attributes of instances are mapped to columns of table.

A “virtual object database” is created that can be used from within the programming language.

Hibernate is a persistence framework which is used to persist data from Java environment to database. Persistence is a process of storing the data to some permanent medium and retrieving it back at any point of time even after the application that had created the data ended.

2. Hibernate Architecture

hibernate-architecture-mini

The above diagram shows minimal architecture of Hibernate. It creates a layer between Database and the Application. It loads the configuration details like Database connection string, entity classes, mappings etc.

Hibernate creates persistent objects which synchronize data between application and database.

hibernate-architecture-compre

The above diagram shows a comprehensive architecture of Hibernate. In order to persist data to a database, Hibernate create an instance of entity class (Java class mapped with database table). This object is called Transient object as they are not yet associated with the session or not yet persisted to a database. To persist the object to database, the instance of SessionFactory interface is created. SessionFactory is a singleton instance which implements Factory design pattern. SessionFactory loads hibernate.cfg.xml file (Hibernate configuration file. More details in following section) and with the help of TransactionFactory and ConnectionProvider implements all the configuration settings on a database.

Each database connection in Hibernate is created by creating an instance of Session interface. Session represents a single connection with database. Session objects are created from SessionFactory object.

Hibernate also provides built-in Transaction APIs which abstracts away the application from underlying JDBC or JTA transaction. Each transaction represents a single atomic unit of work. One Session can span through multiple transactions.

2.1 SessionFactory (org.hibernate.SessionFactory)

A thread-safe, immutable cache of compiled mappings for a single database. A factory for org.hibernate.Session instances. A client of org.hibernate.connection.ConnectionProvider. Optionally maintains a second level cache of data that is reusable between transactions at a process or cluster level.

2.2 Session (org.hibernate.Session)

A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC java.sql.Connection. Factory for org.hibernate.Transaction. Maintains a first level cache of persistent the application’s persistent objects and collections; this cache is used when navigating the object graph or looking up objects by identifier.

2.3 Persistent objects and collections

Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one org.hibernate.Session. Once the org.hibernate.Session is closed, they will be detached and free to use in any application layer (for example, directly as data transfer objects to and from presentation).

2.4 Transient and detached objects and collections

Instances of persistent classes that are not currently associated with a org.hibernate.Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session.

2.5 Transaction (org.hibernate.Transaction)

(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A org.hibernate.Session might span several org.hibernate.Transactions in some cases. However, transaction demarcation, either using the underlying API or org.hibernate.Transaction, is never optional.

2.6 ConnectionProvider (org.hibernate.connection.ConnectionProvider)

(Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer.

2.7 TransactionFactory (org.hibernate.TransactionFactory)

(Optional) A factory for org.hibernate.Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer.

3. Hibernate Configuration

Hibernate configuration is managed by an instance of org.hibernate.cfg.Configuration. An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application’s Java types to an SQL database. The org.hibernate.cfg.Configuration is used to build an immutable org.hibernate.SessionFactory. The mappings are compiled from various XML mapping files or from Java 5 Annotations.

Hibernate provides following types of configurations

  1. hibernate.cfg.xml – A standard XML file which contains hibernate configuration and which resides in root of application’s CLASSPATH
  2. hibernate.properties – A Java compliant property file which holds key value pair for different hibernate configuration strings.
  3. Programmatic configuration – This is the manual approach. The configuration can be defined in Java class.

3.1 hibernate.cfg.xml

This is an alternate way of configuring hibernate. The hibernate.cfg.xml file is a standard XML file which contains all the configuration parameters like database connection, class mappings etc. This file needs to be placed root of CLASSPATH of application.

Below is the sample hibernate.cfg.xml file:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <!-- a SessionFactory instance listed as /jndi/name -->
    <session-factory
        name="java:hibernate/SessionFactory">

        <!-- properties -->
        <property name="connection.datasource">java:/comp/env/jdbc/MyEmployeeDB</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">false</property>
        <property name="transaction.factory_class">
            org.hibernate.transaction.JTATransactionFactory
        </property>
        <property name="jta.UserTransaction">java:comp/UserTransaction</property>

        <!-- mapping files -->
        <mapping resource="net/viralpatel/hibernate/Employee.hbm.xml"/>
        <mapping resource="net/viralpatel/hibernate/Department.hbm.xml"/>

        <!-- cache settings -->
        <class-cache class="net.viralpatel.hibernate.Employee" usage="read-write"/>
        <class-cache class="net.viralpatel.hibernate.Department" usage="read-only"/>
        <collection-cache collection="net.viralpatel.hibernate.Department.employees" usage="read-write"/>

    </session-factory>

</hibernate-configuration>

Once the hibernate.cfg.xml file is created and placed in root of application’s CLASSPATH, the same can be loaded in Hibernate using following API.

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

This above code will load default hibernate.cfg.xml file and all the configuration mentioned in it.

In case you want to override default naming convention and want to have your own configuration file like “employeedb.cfg.xml”, following API can be used:

SessionFactory sf = new Configuration()
    .configure("employeedb.cfg.xml")
    .buildSessionFactory();


Note: Both hibernate.cfg.xml and hibernate.properties files can be provided simultaneously in an application. In this case hibernate.cfg.xml gets precedence over hibernate.properties.

3.2 hibernate.properties

This is the easiest way to get started with Hibernate. Create a file hibernate.properties and place it in root of your applications CLASSPATH.

Below is the sample hibernate.properties file:

hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url= jdbc:mysql://localhost:3306/employee
hibernate.connection.username=root
hibernate.connection.password=swordfish
hibernate.connection.pool_size=1
hibernate.transaction.factory_class = \
    org.hibernate.transaction.JTATransactionFactory
hibernate.transaction.manager_lookup_class = \
    org.hibernate.transaction.JBossTransactionManagerLookup
hibernate.dialect = org.hibernate.dialect.MySQLDialect

For detail description of Configuration parameters, refer this article Hibernate configuration properties.

3.3 Programmatic configuration

We can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). For example:

Configuration cfg = new Configuration()
    .addResource("Employee.hbm.xml")
    .addResource("Department.hbm.xml");

An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:

Configuration cfg = new Configuration()
    .addClass(net.viralpatel.hibernate.Employee.class)
    .addClass(net.viralpatel.hibernate.Department.class);

Hibernate will then search for mapping files named /net/viralpatel/hibernate/Employee.hbm.xml and /net/viralpatel/hibernate/Department.hbm.xml in the classpath. This approach eliminates any hardcoded filenames.

A org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:

Configuration cfg = new Configuration()
    .addClass(net.viralpatel.hibernate.Employee.class)
    .addClass(net.viralpatel.hibernate.Department.class)
    .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
    .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test")
    .setProperty("hibernate.order_updates", "true");

4. Building a SessionFactory

Once the instance of org.hibernate.cfg.Configuration is created using any of the above method, the singleton instance of SessionFactory can be created as follow:

SessionFactory sessions = cfg.buildSessionFactory();

Hibernate does allow your application to instantiate more than one org.hibernate.SessionFactory. This is useful if you are using more than one database.

5. Getting Session instance

As noted above, Session represents a communication channel between database and application. Each session represents a factory of transactions. Session can be created from SessionFactory as follows:

Session session = sessions.openSession(); // get a new Session

Thus, in this article we saw an overview of Hibernate ORM and its architecture. Also we noted its different components like SessionFactory, TransactionFactory, Session etc and APIs to instantiate these objects in your application.

In next tutorial, We will write a Hello World Hibernate program using both XML file based configuration and Annotations.

Stay tuned! :)



27 Comments

  • fhatz 19 June, 2012, 14:44

    very good materials for read for newbie using simple word to explain … keep on the good work… thanks alot!

  • Bad 24 June, 2012, 19:45

    Great article! Very helpful! Thanks!

  • Rayudu 28 June, 2012, 12:46

    Very good article, and very helpfull.. Thanks a lot

  • Shaswati Roy 29 June, 2012, 13:50

    Must say , hibernate architecture in a frame … Thanks a lot!!

  • Ranjit 3 July, 2012, 10:04

    very well articulated, must say a nice piece of work!! Truly helpful for me!!
    Thanks a lot dude!! keep up good works!!

  • Sandy 4 July, 2012, 12:45

    Excellent tutorials but i have one request please organise tutorials in step by step by manner sometime it is difficult to find out tutorials

  • dineshkumar 26 July, 2012, 0:46

    very good article…its very useful for me…..thank u so much

  • Viral 9 August, 2012, 12:05

    Can you show me the package structure of hibernate … I am beginner in hibernate and i want to know where to place which file in package …

  • nikunj 22 August, 2012, 12:05

    thanx hactic

  • Luie jose 27 September, 2012, 17:15

    Great Thanks a lot. please do provide sample code for hibernate using SQL Joins or an example using Hibernate query language.

  • Jag 26 October, 2012, 16:27

    awsome tutorial ., keep on putting sample codes of hibernate.

  • Mithun 21 November, 2012, 15:41

    Hi Viral

    It is a very nice material. I can suggest you to describe in an detailed manner. Though it is okay.
    But it was some more detailed manner, It would be easy for each and everyone.

    Thanks.

  • Ramesh 6 December, 2012, 18:01

    VERY NICE CODING

  • Arun 24 December, 2012, 12:26

    attractive and effective notes….

  • Kalai 3 January, 2013, 11:40

    very easy to understand

  • Rajasekhar Reddy 21 February, 2013, 13:09

    how to manage session in hibernate?

  • Devilfish87 13 May, 2013, 1:02

    Excellent work the article is really well structured understandable even for newbies :)

    Does using org.hibernate.Query (Hibernate query Language ) query.uniqueResult() – affects the JEE application performance and security when comparing with normal methods like findById() ??

    Here is an example :

     Session session = HibernateSessionFactory.getSession();
    		Query query = session.createQuery("from User where Login='" + login + "'");
    		User user = (User) query.uniqueResult(); 

    Thanks

  • mayur Oza 24 October, 2013, 23:25

    Excellent article……

  • Bhabadyuti 20 November, 2013, 10:34

    Excellent tutorial for newbies..

  • Anuj 24 January, 2014, 10:02

    Very good content for the initial learners

  • Jodu 30 January, 2014, 14:39

    Excellent tutorial in order to begin a learning of Hibernate. Thanks a lot.
    A french visitor

  • ram bharath 6 February, 2014, 12:56

    Can you show me the package structure of hibernate … I am beginner in hibernate and i want to know where to place which file in package …and ur code is too easy to understand,thanks a lot

  • ram bharath 6 February, 2014, 13:00

    its too easy to understand

  • Sreekanth 21 February, 2014, 20:29

    Its an excellent tutorial for beginners. Could you please let me know the certification to be done for Hibernate.

  • Ankur 8 April, 2014, 15:22

    This blog about hibernate is amazing.. you made my week.. what I was searching for
    Good work…
    Thanks a lot
    Ankur

  • Dheeresh 13 June, 2014, 21:50

    Very helpful in reminding things…. Thanks Viral

  • nimavat chetna 11 July, 2014, 21:07

    This blog about hibernate is amazing.. you made my week.. what I was searching for
    Good work…
    Thanks a lot

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current day month ye@r *