Pages Navigation Menu

Coding is much easier than you think

Steps to be followed to use Hibernate in Java

Posted by on Mar 15, 2015 in Hibernate | 0 comments

Hibernate To Do List
In our previous tutorial we have learned about Simple Hibernate Application Requirements. In this article we shall explore about the exact flow to use hibernate in a java application.
Following are the Steps to be followed to Use Hibernate in Java

1. Import Hibernate API

Import the following hibernate API.

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;


2. Loading Configuration files

To load hibernate configuration xml, we need to create object of Configuration class and we need to call configure() method in that class.

Configuration cf = new Configuration().configure("hibernate.cfg.xml");

Once configure method is called, the following actions takes place:

  • The configuration object cf will read configuration details from hibernate.cfg.xml file and Stores the data in different variables of a high level hibernate object called SessionFactory.
  • Now this SessionFactory object sf contains all the data regarding the configuration file

So in java we get this configuration details by using the following code.

StandardServiceRegistryBuilder srb = new StandardServiceRegistryBuilder();
ServiceRegistry sr =;
SessionFactory sf = cf.buildSessionFactory(sr);

Note: Once we load the configuration file, the mapping file will be loaded automatically as we have configured the mapping xml in the hibernate configuration file.

3. Creating an object of session

To open a database connection in hibernate, we need to call openSession() method of SessionFactory, now assign this connection to Session interface.

Session session = sf.openSession();
//sf = Object of SessfionFactory 


4. Create a logical transaction

Hibernate needs a logical Transaction to perform insert, update and delete operations into any database. In order to begin a logical transaction in hibernate we need to call beginTransaction() method of Session Interface and assign it to Transaction interface.

Transaction tx = session.beginTransaction();
//session = Object of Session Interface

Note: For selecting an object from the database we do not require any logical transaction in hibernate.

5. Use Session Interface methods

We can use the methods given by Session Interface, to move the objects from java to database and from database to java – Insert object ‘s’ into database
session.delete(s) – Delete object ‘s’ from database
session.update(s) – Update object ‘s’ in the database
session.load(s) – Select object ‘s’ from database

6. Commit Transaction

Now we need to call commit() method of Transaction to perform commit operation using tx.commit();

7. Close Session and SessionFactory

As discussed earlier, when we open a session, a connection to database is created, so once the transaction is complete, we must close that connection via session.close() code and finally we have to close the SessionFactory via sf.close() code.
So the final flow of any hibernate application will be as below

Open Session
Begin Transaction
Commit Transaction
Close Session and SessionFactory


Read More

Generic Hibernate Application Requirements – Annotation

Posted by on Mar 15, 2015 in Hibernate | 0 comments

Hibernate Generic Requirment
The objective of this example is to understand the general requirement to be followed in creating any hibernate application in Java. You may want to look at Hibernate Installation/Setup on Eclipse IDE article if Hibernate is not installed already on your system.
In general any hibernate application, must have the following 3 files,
1) Configuration XML – This file will be used to store database connection information and schema level settings.
2) Entity Class – This class will be java POJO having hibernate annotations.
3) Java file to access this configuration file and write our logic
These files are the minimum requirement to run any hibernate application, in case of complex application we may require many Entity classes.
Note : Number of Entity classes = Number of Tables in database

Hibernate Configuration file

In this mapping file Hibernate gets to know about the type of database and its connection properties as well as about the Entity class.
File: hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"


	<!-- Database connection settings -->
	<property name="hibernate.connection.driver_class">
	<property name="hibernate.connection.username">system</property>
	<property name="hibernate.connection.password">admin</property>
	<property name="hibernate.connection.url">

	<!-- SQL dialect -->
	<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>

	<!-- Echo all executed SQL to sysout -->
	<property name="show_sql">true</property>

	<!-- Drop and re-create the database schema on startup -->
	<property name="">update</property>
	<!-- Map Entity Class -->
    <mapping class="entity.StudentEntity"></mapping>



Entity class

The entity class is where the Hibernate mapping comes into play, this class tells Hibernate what table in the database it has to access, and what columns in that table it should use. For each member variable defined in Entity class you must create a getter and a setter.

package entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "STUDENT")
public class StudentEntity {

	@Column(name = "ID")
	private int id;
	@Column(name = "NAME")
	private String name;
	@Column(name = "DEPARTMENT")
	private String department;
	@Column(name = "COLLEGE")
	private String college;

// Create Getters and Setters

As shown above, the mapping file contains several annotations, listed below are its role:

  • @Entity annotation marks this class as an entity bean
  • @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database.

    The @Table annotation provides four attributes, allowing you to override the name of the table, its catalogue, and its schema, and enforce unique constraints on columns in the table. For now we are using just table name which is STUDENT.

  • @Id Annotations:– In hibernate each entity bean should have a primary key, which you annotate on the class with the @Id annotation. The primary key can be a single field or a combination of multiple fields depending on your table structure.
  • @Column, The @Column annotation is used to specify the details of the column to which a field or property will be mapped. Here the name attribute in @Column permits the name of the column to be explicitly specified.

In our next article we shall learn about Generic Steps to be followed to use Hibernate in any Java application, going forward using this two articles we shall implement Hello World example of Hibernate 4 in Eclipse

Read More

Hibernate Installation/Setup on Eclipse IDE

Posted by on Mar 14, 2015 in Hibernate | 2 comments

Hibernate Logo
In our previous tutorial we got introduced to what hibernate is, and its advantage and disadvantage. In this tutorial you will learn how to install Hibernate and other associated packages to setup an environment for the Hibernate applications.

Environment Used

  • JDK 7 (Java SE 7)
  • Eclipse JUNO IDE
  • Hibernate jars
  • Any RDMS Database(Oracle 10 g in this example)


Setting up development environment

To install Eclipse IDE read this page

Downloading Hibernate

Hibernate Framework is available for downloading straight from its official site. The latest version of this framework for this day is 4.3.8
Simply go to
Choose Stable-4.3.8 final Download option as shown on the picture below:
Once downloaded Unzip the archive files.
Now Create a new Java Project(File -> New -> Java Project) and enter Hibernate4HelloWorld as project name. Create lib sub directory in this project.
Copy all 10 jar files Under lib/required directory of the hibernate distribution that you have downloaded to the lib directory of the “Hibernate4HelloWorld” project.
Those 10 jars are


These are the main jar files to run hibernate related programming,
Additionally, you will need the database driver JAR that Hibernate uses to connect to your database. I use Oracle Express Edition(Oracle XE) and it’s database driver jar is here on Windows:
Copy this ojdbc14.jar to the lib directory of the “Hibernate4HelloWorld” project.
Note: if you have another database management system already installed, then you should replace this database driver JAR with a different database driver JAR. For example, you must download MySQL Connector/J (official JDBC driver for MySQL) from if your database is MySQL.
Now I will create a User library on Eclipse IDE. Then, I will add all JAR files in the Hibernate4HelloWorld\lib directory to this User library and add this User library to the project build path.
Click Project–>Properties on the top menu bar of Eclipse.
User Library
Click Java Build Path–>Add Libraries.
Add library
Then, select “User Library” and click Next button.
User Library2
Then click on User Library button
User Library3
Now in the below screen click New button then enter “Hibernate” as the User library name.
User Library4
Select “Hibernate” User library that we just created and click Add External JARS… button.
User Lib
Select all JAR files in the lib folder of the “Hibernate4HelloWorld” project and click Open button to add all JAR files to “Hibernate” User library. Now “Hibernate” User library is ready and now click on ok.
Add external jars
Finally, select “Hibernate” User library and click Finish button.
User Library5
After adding “Hibernate” User library to “Hibernate4HelloWorld” project, it will look like this:
Hibernet Project structure
In our next article we will learn about Simple Hibernate Application Requirements using Annotation as well as XML Mapping

Read More

Hibernate Eager vs Lazy Fetch Type

Posted by on Oct 22, 2014 in Hibernate | 3 comments

Sometimes you have two entities and there’s a relationship(OneToOne, OneToMany or ManyToMany)  between them.
For example, you might have an entity called University and another entity called Student. The University entity might have some basic properties such as collegeId, name, address, etc. as well as a property called students:

public class University {
 private String collegeId;
 private String name;
 private String address;
 private List<Student> students;

 // setters and getters

Now when you load a University from the database, Hibernate loads its collegeId, name, and address fields for you. But you have two options for students: to load it together with the rest of the fields (i.e. Eagar Fetch) or to load it on-demand (i.e. Lazy Fetch) when you call the university’s getStudents() method.

Pros and Cons

When a university has many students it is not efficient to load all of its students with it when they are not needed. So in suchlike cases, you can declare that you want students to be loaded when they are actually needed. This can be simply done by invoking university’s getStudents() method . This is called lazy loading.

Eager loading is essentially the opposite of Lazy loading, Eager will by default load ALL of the relationships related to a particular object loaded by Hibernate.

So, the long story short here is:

LAZY Fetch = Doesn’t load the relationships unless explicitly “asked for” via getter
EAGER Fetch = Loads ALL relationships

To save memory, Lazy loading is generally used for one to many and many to many relationships. For one to one, generally Eager is used


if you don’t specify this fetch type then Hibernate defaults based on JPA spec.

From the JPA 2.1 spec, the defaults are like so:

  • OneToMany:LAZY
  • ManyToOne: EAGER
  • ManyToMany: LAZY
  • OneToOne: EAGER
  • Columns : EAGER

Another must read

Read More

Hibernate Life Cycle

Posted by on Oct 8, 2014 in Hibernate | 1 comment

Hibernate is picky about your Java objects. Hibernate prefers your objects to be in a certain “state”, and there are four different states that exist inside of the hibernate life cycle. They are-

  1. Transient
  2. Persistent
  3. Detached
  4. Removed

Once you have a firm grasp of the different states that an object can be in Hibernate, you’ll be well on your way to mastering the Hibernate framework. Now let’s get this Hibernate life cycle lesson started.


When ever an object of a pojo class is Created(instantiated) using the new operator then it will be in the Transient state; this object is not associated with any Hibernate Session.  

Hibernate Transient Object

This object don’t have any association with any database table row. In other words any modification in data of transient state object doesn’t have any impact on the database table.  


When the object is in persistent state, then it represent one row of the database, and it is associated with the unique Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes.  
You can create persistent objects via two ways:

  1. Loading the object from the database via Hibernate APIs
  2. Saving the object to the database via Hibernate APIs

Ways to Save an Object
Hibernate has a few different ways to save an object to the database, but the two main ways are as follows:

  1. save()
  2. saveOrUpdate()
  3. persist();

Invoking either of these Hibernate methods will shift your transient object into the persistent state (so long as the save is successful).
Ways to Load an Object
There are quite a few ways to load an object from a database. Here’s a couple that I use the most:

  1. get()
  2. load()
  3. list()

hibernate Persistent Object


if we want to move an object from persistent to detached state, we need to close the session or clear the cache of the session.
hibernate Detached Object

  • Here the reference to the object is still valid and the detached instance can be modified in this state.
  • A detached instance can be reattached to a new Session at a later point in time, making it (and all the modification) persistent again.

This reattaching of object from detached  to persistent state can be done by calling the following methods –

  • update()
  • merge()
  • saveOrUpdate()
  • lock() – It is reattached but not saved.


A persistent object is considered to be in the removed state when a delete() or remove() operation is called on it. Note that Once you’ve deleted an object and moved to the “removed” state, you should no longer use that particular object for any reason.
hibernate Removed Object

Read More

Introduction to Hibernate

Posted by on Apr 19, 2014 in Hibernate | 0 comments

In this to we will learn about what hibernate is, and how to use hibernate in our application and its features.

What is hibernate ?

  • It called as ORM tool (we will learn in subsequent tut)
  • Used in the data layer to save date into the database
  • Implements JPA (JPA is a set of standards which is prescribed for doing any operation in database.

Hibernet cover

1. Problem which Hibernate solves

Mapping member variables to column

Let take a Student class as an example, which has the following fields ID, Name, Department, Phone no, Address, Active.Hibrenet introductionIn a running application we may have lot of such objects, now to save the data in db; I need to create a Student table, in which I will save the Student objects as rows. So here N no of objects equal to N no of row in the table.

This implies that the class corresponds to the table and object of the class corresponds to the rows in the table. In java application, we will have a JDBC to connect to the db, and we will take this Student object, create an insert sql query and do an insert, Now all these data will be stored in db.

Now to select these data, we will create a select query to pull to the records and to store the records we will create a Student object to. So in Java we have data in form of objects, but there is no object in table, So java entity needs to be converted into a table entity, (i.e.) records.

The way we normally convert is by taking each of the values and map to its rows, this mapping is more tedious as we need to convert each object into SQL quires for saving, and for retrieving I have to convert a result set into corresponding java objects.

2. Mapping relationship

For example Student table has a column which is the primary key of another table (Address).
Hibernet example
Here in java side care should be taken to map Student object to Student table and Address object to Address table.

3. Handling data types


To check whether the Student is active or not, in java side, we will create a Boolean variable which hold the value true or false, here in case of Database, we cannot have a column with type Boolean, for this scenario we can either have a char type or int type. So now we have to handle this data type conversion by ourselves.

4. Managing the changes to object state.

Suppose if we want to update any of the field n DB, then we have to pull the object from db, store it in Student object then write a java code to trigger update query.

The above 4 are the most common problem which we face in most of the java application. In our next article we shall learn to set up Hibernate in eclipse.


Read More