Hibernate - Java ORM Framework

                                              Boby Thomas - 23 - 04 -2009


Introduction

In today's internet world, developing high quality application before your competitor release their products is a must to survive. Any delay in upgrading and providing latest technology based solution can take you out of market. Rapid application development is a must in this scenario and no one can afford a failure or a wrong judgment about technology or frameworks. Tested and proven frameworks will be preferred over potential state of the art frameworks as a failure at a later stage in development can be disastrous. Hibernate is one such framework which is widely used, tested and proven for object relational mapping. It helps us with rapid application development with data intensive applications.

 

Object-relational mismatch

Most of the popular programming languages like C++, Java, C#, Ruby etc are object oriented language. Anything and everything will be treated as objects. Application is a collection of objects interacting with each other.

 

What about the data that we saved in the database? Most of the data is stored in relational database. This is understandable as research proved that there are many disadvantages in using OO data models. So we will not see, at least in the near future, a transition from relational database to OO database. So we need to live with relational databases for storing and retrieving data.

 

Now we know, we have to bridge the gap between data in relational databases and our object oriented programming languages. This led to the creation of many ORM frameworks to which bridges the gap between OO programming language and relational databases. Hibernate is one such framework which is around for quite some time and is tested and proven for its quality.

 

What is Hibernate?

  1. Object/relational mapping framework for Java.
  2. Licensed under the Lesser GPL.
  3. Can be used in commercial products.
  4. Build persistent objects following common Java idioms:
  • Association

  • Inheritance

  • Polymorphism

  • Composition

  • Collections API for many relationships.

 

Why Hibernate?

  1. Focus on domain object modeling.
  2. Performance.
  • High performance object caching.

  • Configurable materialization strategies.

  1. Sophisticated query facilities
  • Hibernate Query Language (HQL)

  • Criteria API and Query by Criteria

  • Query by Example.

Using Hibernate

  1. Hibernate can persist POJOs which follow JavaBeans specification.
    • No arg constructor.
    • Getter/setter methods for mapped attributes.
  1. No requirement to inherit from a persistent base class or interface.
  2. Cross-cutting persistence features are declaratively maintained within the Hibernate configuration file and mapping files.
    • Object caching
    • Relationship materialization strategies

Sample Application

Now let?s build a sample application using Hibernate.

What are we going to do?

We will create a questionnaire web application. All the data will be kept in databases. In the main page, we need to list out all possible question categories. On selection of each category, questions corresponding to that category must be displayed to user. On completion of answering calculate the score and give user an option to save their scores in the server. Also give user an option to see high scores for each category.

How are we going to do?

Let us define what we are going to use for our sample application.

  1. Standard Struts Web Application
  2. Deployed on Tomcat 6.0
  3. Persisted to MySQL database
  4. All hand coded, didn?t use automated tools to generate Java classes, DDL, or mapping files

 

Define database tables

First I will create a table for storing categories.

Now let me define another table questions and finally one more table for storing user scores.

 

Mapping classes to tables

Now we need to map the java classes to database tables.

 

Hibernate configuration

Now configure hibernate to link these mapping files.

 

Define classes mapping tables

We define category class.

package org.bpt.question.database;

public class Category {

      private int categoryIndex = 0;

      private String description = "";

      public String getDescription() {

            return description;

      }

      public void setDescription(String description) {

            this.description = description;

      }

      public int getCategoryIndex() {

            return categoryIndex;

      }

      public void setCategoryIndex(int categoryIndex) {

            this.categoryIndex = categoryIndex;

      }

      public String getCategory() {

            return category;

      }

      public void setCategory(String category) {

            this.category = category;

      }

      private String category = "";

}

 

 

Similarly we need to define classes Question and UserScore classes.

 

Access Database

Step 1 - Create session Factory

// Create the SessionFactory from hibernate.cfg.xml

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

 

 

Step 2 - Get a session

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

 

Step 3: Access data

List list = session.createQuery("from Category").list();

 

Data access methods

There are three methods to access data.

1. Hibernate Query Language(HQL)

HQL is a query language similar to SQL. What you have seen in the example is one of the simplest possible HQL query.  

List list = session.createQuery("from Category").list();

 

2. Criteria based

In criteria based queries, you create a criteria object and add all required criterias to the object before using it.

Criteria criteria = session.createCriteria(UserScore.class);

criteria.add(Restrictions.eq("category", category));

criteria.addOrder(Order.desc("score"));

List list = criteria.list();

3. Normal sql

You can use normal sql also with hibernate. Read hibernate documentation for more details.

Performance

Following are few main points, which are implemented in Hibernate. Refer www.hibernate.org for more details.

  • Caching objects.
  • Executing SQL statements later, when needed.
  • Never updating unmodified objects.
  • Efficient Collection Handling.
  • Rolling two updates into one.
  • Updating only the modified columns.
  • Lazy collection initialization.
  • Lazy object initialization.
  • efficient PreparedStatement caching
  • JDBC 2 style batch updates
  • Pluggable connection pooling

 

Reflection

This is a critical issue while deciding as to whether to use hibernate or not. As you can imagine, hibernate relies heavily on reflection. We specify mapping files with class names and hibernate finds out these classes at runtime using reflection. But since most of the latest JVMs implements reflection efficiently, it may not make much of a difference these days.

Instance Pooling

Instance pooling is not implemented in hibernate. This could mean that memory utilization is less efficient. But most of the time, instance pooling may not make much of a difference as every non-primitive data type after loading and passivation in EJB is garbage. So if you look at the amount of objects, which any way needs to be garbage collected, is of significant percentage in most of the real scenarios. While using hibernate, if required, we can create own pool and use Session.load(). We need to take care ourselves to return the object to pool after using.

License

Free/open source - Hibernate is licensed under the LGPL (Lesser GNU Public License). Simply put, you can use it for free. Any modification you make, you need to share it with others too. Refer www.hibernate.org for any changes / more details.

Summary

Developing a persistence layer for java is made too simple by hibernate. If you have n ot tried this yet, it is worth spending some time on hibernate. For more details about hibernate,  click here.


Related Links