Understanding Hibernate ORM for Java/J2EE

Understanding the Hibernate Object/Relational Mapping Solution

Introduction

As you all know, in today’s enterprise environments working with object-oriented software and a relational database can be cumbersome and time consuming. Typically, in an enterprise application, if you are passing objects around and sometimes reach the point where you want to persist them, you will open a JDBC connection, create an SQL statement and copy all your property values over to the PreparedStatement or into the SQL string you are building. This may be easy for a small value object, but for an object with many properties, you may face many difficulties. As myself have experienced and most of you Java Programmers have seen, the object-relational gap quickly becomes very wide if you have large object models. Thus, the activities involved in persisting data are tedious and error-prone. So, we go for Object-relational mapping (O/R mapping) which is a common requirement of many software development projects.

If you are working with object-orientated programming and relational databases, you will surely have noticed that these are two different paradigms. The relational model deals with relations, tuples, and sets—it is very mathematical by nature. The object-orientated paradigm however deals with objects, their atributes and associations to each other. As soon as you want to make objects persistent using a relational database you will notice: There is a rift between these two paradigms, the so-called object-relational gap. A object-relational mapper (ORM) will help you bridge that gap.

If we also take into consideration the inevitable change of requirements, we’re in serious trouble: The data storage structure must be kept in sync with the source code. By using ORM, we can make the application portable to all databases.

Why ORM?

The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema. So, what can an ORM do for you? A ORM basically intends to takes most of that burden of your shoulder. With a good ORM, you have to define the way you map your classes to tables once; which property maps to which column, which class to which table, and so forth.

With a good ORM, you can take the plain Java objects you use in the application and tell the ORM to persist them. This will automatically generate all the SQL needed to store the object. An ORM allows you to load your objects just as easily: A good ORM will feature a query language too. The main features include:

  1. Less error-prone code
  2. Optimized performance all the time
  3. Solves portability issues
  4. Reduce development time

Hibernate

Hibernate is in my opinion the most popular and most complete open source object/relational mapping solution for Java environments. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time; otherwise, spent with manual data handling in SQL and JDBC. It manages the database and the mapping between the database and the objects.

Hibernate’s goal is to relieve the developer from 95 percent of common data persistence related programming tasks. Hibernate adapts to your development process, no matter if you start with a design from scratch or work with a legacy database.

Hibernate generates SQL for you, relieves you from manual result set handling and object conversion, and keeps your application portable to all SQL databases. Hibernate allows you to store, fetch ,update and delete any kind of objects. Hibernate lets you develop persistent classes following common Java idiom—including association, inheritance, polymorphism, composition, and the Java collections framework.

The Hibernate Query Language, designed as a minimal object-oriented extension to SQL, provides an elegant bridge between the object and relational worlds.

Key features include:

  1. Integrates elegantly with all popular J2EE application servers, Web containers and in standalone applications. Hibernate is typically used in Java Swing applications, Java Servlet-based applications, or J2EE applications using EJB session beans.
  2. Free/open source. Hibernate is licensed under the LGPL (Lesser GNU PublicLicense).critical component of the JBoss Enterprise Middleware System (JEMS) suite of products.
  3. Natural programming model. Hibernate supports natural OO idiom; inheritance, polymorphism, composition, and the Java collections framework.
  4. Extreme scalability. Hibernate is extremely performant, has a dual-layer cache architecture, and may be used in a cluster.
  5. The query language. Hibernate addresses both sides of the problem; not only how to get objects into the database, but also how to get them out again.
  6. EJB 3.0. Implements the persistence API and query language defined by EJB 3.0 persistence.

What Is a Persistent Class?

Hibernate provides transparent persistence; the only requirement for a persistent class is a no-argument constructor. In a persistent class, no interfaces have to be implemented and no persistent superclass has to be extended. The Persistent class can be used outside the persistence context.

Persistent classes are classes in an application that implement the entities of the business problem. Let me illustate this with a simple eg : login entity. The persistent class can be like:

public class Login {
   /** persistent fields */
   private String userName;
   private String userPassword;

   /** default constructor */
   public Login () {
   }

   public String getUserName() {
      return this.userName;
   }

   public void setUserName(String userName) {
      this.userName = userName;
   }

   public String getUserPassword() {
      return this.userPassword;
   }

   public void setUserPassword(String userPassword) {
      this.userPassword = userPassword;
   }

}

Persistent classes have, as the name implies, transient and also persistent instance stored in the database. Hibernate makes use of persistent objects commonly called as POJO (Plain Old Java Object) programming model along with XML mapping documents for persisting objects to the database layer. POJO refers to a normal Java object that does not serve any other special role or implement any special interfaces of any of the Java frameworks like a Java Bean.

The Ultimate Goal

Take advantage of those things that relational databases do well, without leaving the Java language of objects/classes. I will say, the ultimate aim is: Do less work, Happy DBA.

Hibernate Architecture

I believe Hibernate provides persistence as a service, rather than as a framework. I will show two common architectures incorporating Hibernate as a persistence layer. As I have already explained, for persisting objects Hibernate makes use of persistent objects commonly called as POJO, along with XML mapping documents.

In Web (two-tiered) Architecture, Hibernate may be used to persist JavaBeans used by servlets/JSPs in a Model/View/Controller architecture.

In Enterprise (three-tiered), Architecture Hibernate may be used by a Session EJB that manipulates persistent objects.

Typical Hibernate code

sessionFactory  = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx  = session.beginTransaction();

//Data access code

session.save(newCustomer);
tx.commit();
session.close();

The first step in a Hibernate application is to retrieve Hibernate Session. Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create a Hibernate session by reading the Hibernate configuration file hibernate.cfg.xml. After specifying transaction boundaries, the application can make use of persistent Java objects and use the session to persist to the databases.

Getting Started with Hibernate

  1. Download and install Hibernate. Hibernate is available for download at http://www.hibernate.org/.
  2. Include the hibernate.jar file in the working directory.
  3. Place your JDBC driver jar file in the lib directory.
  4. Edit the Hibernate configuration files, specifying values for your database. (Hibernate will create a schema automatically.)

More by Author

Must Read