ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Hibernate - An overview

Updated on November 21, 2008
Click thumbnail to view full-size


In real time, developing enterprise applications involves huge effort to store the business objects in the database (Usually 70%). That is, most complicated part of the business logic is in storage of the object to the database: Opening connection to database, reading data from database, writing data to database and closing the connection to database. Following are the problems in those applications:

  • Affects the maintainability
  • Code is scattered
  • Too expensive
  • Difficult to fix bugs
  • Difficult to manage the Database connections

What could be the solution?

Need to have a mechanism to isolate the database persistent code and modify it (only) when there is a change in the database design.

The Object/Relational Mapping Problem

        It is important to know what is “Object/Relational Mapping Problem” in this context.

In Object oriented systems (OOS), entities are represented as Objects and classes; database is used to persist those objects.



Now, WAIT!!!

What if we need to modify the design of our database after having developed few pages?

Do not worry. Fortunately, we already have a solution: HIBERNATE



Hibernate – Overview

What is it?

  • An open source object/relational mapping tool for Java
  • Lets to develop persistent classes and persistent logic without caring how to handle the data

What it does?

  • Map from Java classes to database tables and from Java data types to SQL data types


  • To relieve the developer from 95% of common data persistence related programming tasks.


What should I do?

  • You only need to write a simple POJO (Plain Old Java Object), create an XML mapping file and call few Hibernate APIs.


Hibernate – Architecture

Click thumbnail to view full-size

Hibernate architecture has following three main components: 

Connection Management 

Connection management service provides efficient management of the database connections. Database connection is the most expensive part of interacting with the database as it requires a lot of resources to open and close the database connection. This service makes the database handling easy.



Transaction management 

Transaction management service provides the ability for the user to execute more than one database statement at a time.

 Object relational mapping 

Object relational mapping is technique of mapping the data representation from an object model to a relational data model. This part of the hibernate is used to select, insert, update and delete the records from the underlying table. When we pass an object to a method, Hibernate reads the state of the variables of that object and executes the necessary query.



Hibernate is a very good tool for object relational mapping, but in terms of connection management and transaction management, it is lacking in performance and capabilities. That is why, Hibernate is being used with other connection management and transaction management tools. For example apache DBCP is used for connection pooling with the Hibernate.

 Hibernate provides a lot of flexibility in use. It is called "Lite" architecture when we only use the object relational mapping component. While in "Full Cream" architecture all the three component Object Relational mapping, Connection Management and Transaction Management) are used.


Hibernate – Features

  • Free software. LGPL License.
  • Powerful Object oriented query language
  • XML Mapping documents - Human readable format
  • High Performance
  • Integration with J2EE architecture
  • Support for a wide range of databases

HQL – Hibernate Query Language

What it is?

  • HQL is case-insensitive, except for the names of the Java Classes and properties.
  • Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application.

  • Uses Classes and properties instead of tables and columns
  • Very powerful and it supports Polymorphism, Associations, Much less verbose than SQL
  • Other options that can be used while using Hibernate are:

                 a.) Query By Criteria (QBC)

                 b.) Query By Example (QBE)


Why to use HQL?

  • Full support for relational operations
  • Return result as Object
  • Polymorphic Queries
  • Easy to Learn
  • Support for Advance features
  • Database independent


How it looks like? 

Any Hibernate Query Language may consist of following elements:

  • Clauses

  • Aggregate functions

  • Subqueries


  • from 
  • select
  • where
  • order by
  • group by 

Aggregate functions

  • avg(...), sum(...), min(...), max(...)  
  • count(*)  
  • count(...), count(distinct ...), count(all...)




  • Query within another query 
  • Hibernate supports Subqueries if the underlying database supports it.

Demonstration of Hibernate Application

Application to add, update, delete or search a user in the database.

Database: ORACLE

Click thumbnail to view full-size


Syntax for USERS Table Creation:


Click thumbnail to view full-size

Step 2: Writing the first Java file

Remember we have a table “users” in the database.

package com.xpd.hibernate;


* @author xPD



public class User {

               private long userId = 0 ;

               private String firstName = "";

               private String lastName = "";

               private int age = 0;

               private String email = "";

               public int getAge() { return age; }  

public void setAge(int age)


    this.age = age;


public String getEmail()


    return email;


public void setEmail(String email)

{ = email;


public String getFirstName()


return firstName;



Click thumbnail to view full-size


Let us now add the mapping file to the Hibernate configuration file hibernate.cfg.xml. After adding the mapping resource entry, the hibernate.cfg.xml looks like this.

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

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN" ""> <hibernate-configuration> <session-factory>

<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

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

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


<!-- Set AutoCommit to true -->

<property name="connection.autocommit">true</property>

<!-- SQL Dialect to use. Dialects are database specific -->

<property name="dialect">net.sf.hibernate.dialect.OracleDialect</property>

<!-- Mapping files -->

<mapping resource="com/xpd/hibernate/User.hbm.xml" />




Step 4: Writing the Business Component

Write a business component that can perform different operations on the User object.

package com.xpd.hibernate.client;

import org.hibernate.Session;

import com.xpd.hibernate.User;



* UserManager

* @author xpd


public class UserManager {

private Session session = null; public UserManager (Session session)


if (session == null)

    throw new RuntimeException ("Invalid session object. Can't instantiate userManager")

    this.session = session;


public void saveUser(User user)

{ (user);


public void updateUser(User user)


      session.update (user);



public void deleteUser(User user)


      session.delete (user);



Step 4.1: Writing the Test Client

package com.xpd.hibernate.client; 

import org.hibernate.*;  import org.hibernate.cfg.Configuration;  import com.xpd.hibernate.*;  public class TestClient { 

/*     * This method builds a default user to check if the Hiernate configuration is working or not 

   */   public User buildUser()  {  

 User user = new User ();

user.setFirstName ("Durai");

user.setLastName ("Murugan");

user.setAge (21);

user.setEmail (;

return user;



* This method gets the default SessionFactory configured in hibernate.cfg.xml and opens a session


public Session openSession()


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

      Session session =sessionFactory.openSession ();

      return session;


public User testSaveUser(UserManager manager)


    User user = buildUser ();

    manager.saveUser (user);

    System.out.println ("User saved with ID = " user.getUserId ());

    return user;


public void testUpdateUser(UserManager manager, User user)


    user.setFirstName ("Andrew");

    manager.updateUser (user);

    System.out.println("User updated with ID = " user.getUserId());



public void testDeleteUser(UserManager manager, User user)


   manager.deleteUser (user);

   System.out.println ("User deleted with ID = " user.getUserId ());


 public static void main(String[] args)


    TestClient client = new TestClient ();

    Session session = client.openSession ();

    UserManager manager = new UserManager (session);

    User user = client.testSaveUser (manager);

    client.testUpdateUser (manager, user);

    client.testDeleteUser (manager, user); session.flush ();



Click thumbnail to view full-size

 Add the following method in TestClient.

public void testFindByAge(UserManager manager)


       java.util.Iterator users = manager.getUsersByAge(30).iterator();

      while (users.hasNext())


          User user = (User);

          System.out.println ("User found with ID=" user.getUserId () "\n" "\tName=" user.getLastName () "\n" "\tEmail=" user.getEmail () "");



Add the call to this method in main. To do this, add the following line in

main.client.testFindByAge (manager);

Hibernate – Advantages

  • Less Development Time
  • Hibernate is Free under LGPL:Hibernate can be used to develop/package and distribute the applications for free
  • Robust and high performance
  • Avoids writing too many queries
  • Database independent 

 The Hibernate Alternative

  • Can use plain SQL queries to store and retrieve data. It does not provide maximum of the features provided by Hibernate.
  • Can use Enterprise Java Beans. But again, need to see if you really have the requirements of an EJB container.
  • Can use the Spring framework to implement a DAO layer which would centralize as well as minimize any future need to change persistence implementations.
  • There are many other Object/Relation mapping products available like OJB (ObJectRelationalBridge), Torque, Castor, Cayenne, TJDO etc. 

Help us to improve the content

How do you rate this article?

See results


    0 of 8192 characters used
    Post Comment
    • OrielGour profile image


      6 years ago

      really cool page with perfect example about how to use Hibernate!

    • profile image


      8 years ago

      Very easy to understand everything

    • profile image


      8 years ago

      Very succinct and nicely done. Great non-biased post.

    • bskvsdm profile imageAUTHOR


      10 years ago from Bangalore

      Hi Manikandan,

      Thank you for your comments. Please keep posted your comments to improvise our contents and delivery.

      Durai / Sanjai.

    • profile image


      10 years ago

      Hi This web page is very super


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)