Hibernate is a very powerful and high performance object/relational persistence framework. It is used to develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections.

Hibernate uses runtime reflection to determine the persistent properties of a class rather than utilizing bytecode processing or code generation. The objects to be persisted are defined in a mapping document, which serves to describe the persistent fields and associations, as well as any subclasses or proxies of the persistent object.

Hibernate – Motivation

  • It's used as a main part in JBoss, one of the most popular Application-Servers (and the most popular Open Source AS)
  • It's very common and widely used
  • Lot of documentation
  • Easy to use.

Hibernate – Brief Overview

This diagram shows Hibernate using the database and configuration data to provide persistence services
(and persistent objects) to the application.

Hibernate – Detailed Overview

The "full cream" architecture abstracts the application away from the underlying JDBC / JTA APIs and lets take Hibernate care of the details.

A Hibernate application consists of 4 parts:

  • Hibernate Properties File
  • Hibernate Mapping (XML) File
  • Hibernate Java Library
  • HQL (Hibernate Query Language)

and also

  • Java Class Files
  • Database Schema

Hibernate – Example

To understand the concept, lets take an example. Consider an office environment where each employee has some boss and there is one employee who has no boss (the real boss). In software terms, we will represent this with one class called employee. The class has one attribute called name of type String and the relationship is self relationship and its Many to one. That is, many employees can have one boss.

Java class for employee will be:

Java Code:
package java_hybernate;

public class Employee
	private Long id; 
        private String name;

	private Employee boss;
	protected Employee() {} // Hibernate requires this
	public Employee(String name) {
		this.name = name;

	public Long getId() {
		return id;

	private void setId(Long id) {
		this.id = id;

	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;

	public Employee getBoss() {
		return boss;

	public void setBoss(Employee boss) {
		this.boss = boss;
The above class ‘Employee’ is quiet simple. I declared private variables and their getters and setters. Obviously getters and setter are public. This to note is I created a variable called ‘boss’ of type Employee. It will hold the object pointing to the boss of an employee. We also have getter and setter for ‘boss’.

Now lets talk about the database for this very example. We will have a table with 3 fields. I will use MySQL for this example. Script to create the required table:

Java Code:
# Database: hibernate_test
# Table: 'employee'

CREATE TABLE `employee` (
`ID` int(11) NOT NULL auto_increment,
`NAME` varchar(80) default '',
`BOSS_ID` int(11) default '0',
Hibernate – Mapping File

Mapping file is required to map attributes of Java class to database fields. Following information is required for creating a mapping file.

  • Class
  • Id
  • Properties
  • Relationships

Hibernate – Mapping File (Class)

  • name: Fully qualified name of the persistent class (or interface)
  • table: Name of its database table
  • discriminator-value: Used to distinguish objects when using a single table

Java Code:
Lets consider a simple example:


Java Code:
<class name="hello.Employee” table="employee">
Hibernate – Mapping File (Id)

Hibernate’s classes mapped to database table must declare the primary key column of the DB table.

Java Code:
name="propertyName" type="typename" column="column_name"
<generator class="generatorClass"/>
  • name: Name of the Identifier property
  • column: Name of the primary key column
  • generator class: Method how the OIDs are generated. Possible values: native (recommended), identity, sequence, hilo, uuid, …

Lets consider a simple example:


Java Code:
<id name="id” column="ID">
<generator class=“native"/>
Hibernate – Mapping File (Property)

Hibernate’s mapping file uses <property> element to declare a persistent, JavaBean style property of the class.

Java Code:
  • name: Name of the Property
  • column: Name of the mapped database column

Lets consider a simple example:


Java Code:
<property name="name” column="NAME"/>
Hibernate– Mapping File (Relationships)

A many-to-one reference in Hibernate’s mapping file is analogous to a simple Java reference. It is the same as the one-to-one situation except there is no requirement to have a shared Primary Key. Instead a Foreign Key is used.

Java Code:
<class name="Foo" table="foo">
<many-to-one name="bar" column="bar_id"/>
Following variants can be used:
one-to-one, many-to-one, composite-id, set, one-to-many, many-to-many, map, components, subclass, joined-subclass

Lets consider a simple example:


Java Code:
<many-to-one name="boss” column="BOSS_ID"/>
One to many relationship example:

Table structure:

Java Code:
Java Code:
<set name="projects" inverse="true"
<key column="CUSTOMER_ID"/>
<one-to-many class="Project"/>
One to many relationship example:

Table structure:

Java Code:
Java Code:
<set name="project_participation"
<key column="EMPLOYEE_ID"/>
<many-to-many class="Project"
Hibernate - Mapping of the class hello.Employee

Save this in a file named Employee.hbm.xml and put it in the directory where your class hello.Employee resides.

Java Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<class name="hello.Employee" table="employee">
<id name="id" column="ID">
<generator class="native"/>
<property name="name" column="NAME"/>
<many-to-one name="boss"
Hibernate – Initialize runtime environment

Following code initializes the Hibernate’s runtime environemnt. You have to use it before start persisting data using hibernate

Java Code:
// Import Statements
import org.hibernate.*;
import org.hibernate.cfg.*;
// And then inside your class
// Looks for mapping files in same classpath location as class
Configuration cfg = new Configuration()
// This binds you to a database configuration
SessionFactory _sessions = cfg.buildSessionFactory();
Hibernate – Example (Create and Save an Employee)

Consider that you have to create and save an employee in the database using Hibernate. We are continuing the same employee/boss example as given above. First initialize hibernate runtime environment as told before and then use following code:

Java Code:
// Open a Session and a Transaction
Session session = _sessions.openSession();
Transaction trans = session.beginTransaction();
Employee emp = new Employee("Dave Morris");
// Flush all
Hibernate Java framework will generate the required SQL.

Java Code:
(?, ?)
Hibernate – Example (Retrieving all Employees)

Considering the same example, now we want to retrieve all the employees. We will print the number of employees, along with their names. Iterator is used to go through each employee.

Java Code:
import java.util.List;
import java.util.Iterator;
List employees = session.createQuery(
"from Employee emp order by emp.name asc").list();
System.out.println(employees.size() + " employee(s) found:");
for(Iterator iter=employees.iterator(); iter.hasNext(); ) {
Employee e2 = (Employee)iter.next();
Hibernate Java framework will generate the required SQL.

Java Code:
employee0_.ID as ID0_,
employee0_.NAME as NAME0_,
employee0_.BOSS_ID as BOSS3_0_
from employee employee0_
order by employee0_.NAME asc
Hibernate – Example (Modifying an Employee)

Considering the same example, now we want to modify an employee using Hibernate. Its also easy. We have to provide the primary key of employee whose name is to be changed.

Java Code:
Employee emp = (Employee)session.load(Employee.class, Long.valueOf("1"));
emp.setName("Imran Khan");
// Commit Transaction
Hibernate Java framework will generate the required SQL. Just note that we simply entered few values and hibernate generated SQL script.

Java Code:
employee0_.ID as ID0_0_,
employee0_.NAME as NAME0_0_,
employee0_.BOSS_ID as BOSS3_0_0_
from employee employee0_
where employee0_.ID=?
update employee
set NAME=?, BOSS_ID=?
where ID=?
Hibernate – Example (Deleting an Employee)

Considering the same example, now we want to delete an employee using Hibernate. We have to provide the primary key of employee whose name is to be changed (as we did while modifying an employee.

Java Code:
Employee emp = (Employee)session.
load(Employee.class, Long.valueOf("1"));
// Commit Transaction
Hibernate Java framework will generate the required SQL.

Java Code:
employee0_.ID as ID0_0_,
employee0_.NAME as NAME0_0_,
employee0_.BOSS_ID as BOSS3_0_0_
from employee employee0_
where employee0_.ID=?
from employee
where ID=?
Hibernate – How to run it

Running an application developed using Hibernate can be tricky for newbies. Just remember the following settings and you won’t get lost.
Set the environment variables and include all necessary libraries into the Classpath. Because there are so many libraries, the best way is to include all JAR-files from $HIBERNATE_HOME and $HIBERNATE_HOME/lib.

Hibernate – Logging

Logging is very important these days. Suppose you developed an application and it passed all the tests and was delivered to the client. Now, after few weeks he reported that the application crashed while working. How you will know what caused that crash? You have to spend many hours even days trying to figure that caused that failure. If you had enabled logging, you could simple read log files and track the problem area.

Hibernate uses Log4J for logging.

Log4j is an OpenSource logging API developed under the Jakarta Apache project. Log4j is widely used for logigng purpose because it is fully configurable, robust, reliable, easily extendible, and easy to implement framework. It helps debugging and monitoring Java applications. Lot of online material is available which can help newbies in getting familiar with this.

To enable this, create a file called log4j.properties and put it in the same directory like the hibernate.properties.



Java Code:
# Direct log messages to stdout
# Root logger option
log4j.rootLogger=INFO, stdout
# Hibernate logging options
# Log JDBC bind parameter runtime arguments
Hibernate Tools

You can use following tools for Hibernate:

  • Eclipse Integration (i.e. XML-support)
  • DDL schema generation from a mapping file (hbm2ddl)
  • Java source generation from a mapping file (hbm2java)

Middlegen (mapping file generation from an existing database schema) is a third party tool that can be used for Hibernate.