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


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.


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. – 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"


    <!-- a SessionFactory instance listed as /jndi/name -->

        <!-- 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">
        <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"/>



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()

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


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

Below is the sample file:

hibernate.connection.url= jdbc:mysql://localhost:3306/employee
hibernate.transaction.factory_class = \
hibernate.transaction.manager_lookup_class = \
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()

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

Configuration cfg = new Configuration()

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()
    .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! :)

Get our Articles via Email. Enter your email address.

You may also like...


  1. fhatz says:

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

  2. Bad says:

    Great article! Very helpful! Thanks!

  3. Rayudu says:

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

  4. Shaswati Roy says:

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

  5. Ranjit says:

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

  6. Sandy says:

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

  7. dineshkumar says:

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

  8. Viral says:

    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 …

  9. nikunj says:

    thanx hactic

  10. Luie jose says:

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

  11. Jag says:

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

  12. Mithun says:

    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.


  13. Ramesh says:


  14. Arun says:

    attractive and effective notes….

  15. Kalai says:

    very easy to understand

  16. how to manage session in hibernate?

  17. Devilfish87 says:

    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(); 


  18. mayur Oza says:

    Excellent article……

  19. Bhabadyuti says:

    Excellent tutorial for newbies..

  20. Anuj says:

    Very good content for the initial learners

  21. Jodu says:

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

  22. ram bharath says:

    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

  23. ram bharath says:

    its too easy to understand

  24. Sreekanth says:

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

  25. Ankur says:

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

  26. Dheeresh says:

    Very helpful in reminding things…. Thanks Viral

  27. nimavat chetna says:

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

  28. Shiva says:

    This article is mirror of official Hibernate Documentation (Tutorial)

  29. subbareddy says:


    This blog is very nice. But I have a doubt in hibernate. If I want to configure 2 or more databases in single cfg file. It is possible or not? If it is possible, How can I get individual database connection? Can you please explain with one example.

  30. Ilavarasan Pandian says:

    Nice one , simple English and good explanation

  31. nimbark paresh says:

    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 *