Hibernate - An overview

Click thumbnail to view full-size

Introduction

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

Why?

  • 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 Session.save() 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

Clauses 

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

Aggregate functions

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

 

 

Subqueries 

  • 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:

CREATE TABLE USERS ( USER_ID NUMBER PRIMARY KEY, FIRST_NAME VARCHAR (20), LAST_NAME VARCHAR (20), AGE NUMBER, EMAIL VARCHAR (40) );

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)

{

    this.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" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <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" />

</session-factory>

</hibernate-configuration>

 

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)

{

      session.save (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 (durai.murugan@company.com);

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) users.next();

          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. 

More by this Author


Comments 5 comments

Manikandan 8 years ago

Hi This web page is very super


bskvsdm profile image

bskvsdm 8 years ago from Bangalore Author

Hi Manikandan,

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

Durai / Sanjai.


Dennis 6 years ago

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


Sadat 6 years ago

Very easy to understand everything


OrielGour profile image

OrielGour 4 years ago

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

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Help us to improve the content

    How do you rate this article?

    • Excellent
    • Good
    • Average
    • Bad
    • Very bad
    See results without voting
    Click to Rate This Article
    working