Hibernate framework Introduction

With continuation from my last post


If we want to master on any new technology, it requires enormous effort.  Hibernate is not an exception from that.  But, Hibernate framework is really simple to master as well as to make it use over business scenarios.  Here is the below list of benefits or advantages of Hibernate Framework,

  1. Hibernate framework is the implementation of Object-Relational Mapping technique.
  2. Easily map JAVA objects with Relational tables.
  3. Converts JAVA data types to Relational data types easily.
  4. Highly overcome the problems that originate because of Impedance mismatch.
  5. Allows developers to focus on business model rather than on database interactions.
  6. Hibernate is database portable. It supports most of the databases available in the market.
  7. Little changes in XML mapping is enough for any complex changes if required.
  8. Provides various query handling capabilities. No need to write database specific queries.
  9. Hibernate provides two level of cache.
  10. Hibernate supports Hibernate Query Language, which can be used to create object queries.
  11. Finally, Hibernate does not replace JDBC.  Rather, it overcomes the limitations of JDBC.
  • Hibernate acts as a bridge between an application and the underlying database that stores data.
  • Hibernate uses the various mapping files that represent persistent JAVA objects.
  • Hibernate maps each properties of JAVA objects to the specific columns of tables in the underlying database.


Hibernate Architecture:

It has 3 major components

  1. Object Relational Mapping
  2. Connection Management
  3. Transaction Management


Object Relational Mapping: Maps the data in Object model to the Relational Model

Connection Management: Focuses on database connections and helps us for managing the database connections.

Transaction Management: Controls various database queries and transactions. It provides built-in data querying and retrieval capabilities, which does not require us to write database specific queries.


Hibernate Database Configuration:

We need make the JAVA application and Hibernate system to work as a unit.  For that, we need to configure Hibernate with a database for each storage and retrieval of data from underlying database.  So that JAVA application can easily interact with database system with the help of Hibernate system by passing the JAVA persistence objects to and fro for storage and retrieval.

Our JAVA application may deployed in any of the following environments

  • Managed
  • Non-Managed

Managed environment refers to server-based environment where a application is managed by server containers.  Example application servers are JBOSS, Websphere, etc.,

Non-Managed environment refers to stand alone environment where application themselves need to manage everything right from connection management, transaction services, caching services, etc.,

Java application configured with Hibernate is portable in any environments.


Things needed to configure Java application with Hibernate:

  • Database connection parameters (like URL, hostname, port, db driver name, username and password)
  • Caching parameters
  • Persistence classes to manage
  • Mapping of Persistence classes to specific tables information.


Hibernate provides two configuration files:

  1. hibernate.properties—a Java properties file
  2. hibernate.cfg.xml—an XML file.

We can use either or both of these options.  But, when we use both, hibernate.cfg.xml file overrides hibernate.properties file.

The hibernate.cfg.xml configuration file provides various properties,

By default, Hibernate loads the hibernate.cfg.xml file and the mapping files present in the class path, and sets the properties provided in these files.

Configuration class in Hibernate

Alternatively, we can set configuration properties and load mapping files programmatically, like below,

Configuration config = new Configuration();

config.addResource( “mapping document”);


config.addClass( classname );

By default, Hibernate searches the mapping document in the class path. However, if you want to load a mapping document from a location other than the class path, you must specify the full path of the mapping file in the addResource() method.




By default, Hibernate configuration properties are set using the hibernate.cfg.xml file. You can, however, set specific properties in addition to those mentioned in the configuration file programmatically. For instance, the code

config.addResource( “mapping document”).addProperty(“hibernate.dialect”,”org.hibernate.dialect.MySQLDialect”);

enables you to not only load a mapping document, but also add the hibernate.dialect property programmatically.

From the hibernate documentation, The org.hibernate.cfg.Configuration is meant only as an initialization-time object.   Usually an application will create a single Configuration, build a single instance of SessionFactory and then instantiate Sessions in threads servicing client requests. A new Configuration will use the properties specified in hibernate.properties by default.

Configuration() – default constructor

addFile(File xmlFile) –  Read mappings from a particular XML file

addURL(URL url) – Read mappings from a URL

addJar(File jar) – Read all mappings from a jar file

addProperties(Properties extraProperties) – Add the given properties to ours.

buildSessionFactory() – Create a SessionFactory using the properties and mappings in this configuration.  The SessionFactory will be immutable, so changes made to this Configuration after building the SessionFactory will not affect it.


SessionFactory is an interface that represents an immutable cache of compiled mappings for a single database specified in the hibernate.cfg.xml file.

SessionFactory is a global factory responsible for a particular database. If you have several databases, for easier startup you should use several <session-factory> configurations in several configuration files.


  • A Hibernate application will have only one SessionFactory instance that will be instantiated when the application is started.
  • SessionFactory instances are thread-safe, so they can be simultaneously accessed by multiple threads without hampering the function of the application.

Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.

Configuration configuration = new Configuration();
configuration.setProperty("hibernate.connection.username", "admin");
configuration.setProperty("hibernate.connection.password", "admin");
configuration.setProperty("hibernate.show_sql", "true");
SessionFactory sessionFactory = configuration.buildSessionFactory();

Sample Hibernate Configuration file from Hibernate Reference Document
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
         <!-- Database connection settings -->
        <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 -->
        <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>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
         <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>


SessionFactory has various methods

openSession() –  Open a Session.

isClosed()– Is this factory already closed?

getCache() –  Obtain direct access to the underlying cache regions.  SessionFactory represents the second level cache of data that can be reused among transactions, and controls the overall functioning of the Hibernate application.

close() – Destroy this SessionFactory and release all resources (caches, connection pools, etc).

The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.

SessionFactory provides second level cache.  The below shows options to disable the second level cache

    <!– Disable the second-level cache  –>

        <property name=”cache.provider_class”>org.hibernate.cache.NoCacheProvider</property>

Optionally maintains a second level cache of data that is reusable between transactions at a process or cluster level.



A org.hibernate.Session interface is designed to represent a single unit of work. A session represents a conversation between an application and a database. It is a non-threadsafe object that can span multiple business transactions, each of which may span multiple database transactions.

The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes.

Once all transactions associated with a session are complete, the session must be closed and discarded.

Sessions are used to persist objects, query persistent objects, and then convert persistent objects into transient objects. Hibernate provides the Session class to create and manage sessions. A SessionFactory instance can have one or more session instances to represent a particular business transaction.

A typical transaction should use the following idiom:

 Session sess = sessionfactory.openSession(); //to instantiate a Session
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 finally {

If the Session throws an exception, the transaction must be rolled back and the session discarded. The internal state of the Session might not be consistent with the database after the exception occurs.

In a managed environment, the application can access the current session by calling the sessionFactory.getCurrentSession() method.

First, you can call it as many times and anywhere you like once you get hold of your org.hibernate.SessionFactory. The getCurrentSession() method always returns the “current” unit of work.


Due to the below setting, the context of a current unit of work is bound to the current Java thread that executes the application.

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

 Session is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the org.hibernate.Session from the thread and closes it for you. If you call getCurrentSession() again, you get a new org.hibernate.Session and can start a new unit of work.

Session interface various methods, few listed below

beginTransaction() – Begin a unit of work and return the associated Transaction object.

close() – End the session by releasing the JDBC connection and cleaning up.

contains(Object object) – Check if this instance is associated with this Session. Checks that the persistence object is in cache.

delete(Object object) – Remove a persistent instance from the datastore (database).

evict(Object object) –  Remove this instance from the session cache.

flush() – Force this session to flush.  It synchronizes persistence objects in memory with those in database. Typically used before committing a transaction and closing a session.

isConnected() – Check if the session is currently connected.

isOpen() – Check if the session is still open.

Hibernate Connection Pool

A connection pool is a cache of database connections. A Hibernate application can use a connection pool to maintain a collection of database connections when database requests are made, without having to open separate connections for each request.

Hibernate supports three connection pooling services: C3P0, Apache’s DBCP library, and Proxool.

You can configure connection pools for a Hibernate application using the options available in the hibernate.cfg.xml file.


A transaction is a group of operations that constitute a single unit of work.

If one of the operations fails, any changes made in response to other operations in the transaction are rolled back, causing the transaction to fail.

By default, Hibernate uses JDBC transactions, which are associated to a Session class and instantiated using the session.beginTransaction() method.

The Transaction class is used to group and manage operations in Hibernate.

Various methods of Transction

          Begin a new transaction.

          Flush the associated Session and end the unit of work

          Force the underlying transaction to roll back.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: