Hibernate : Need and Setup

Hibernate is an ORM tool (object-relational mapping). providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate is a persistence framework which is used to persist data from Java environment to database. Persistence is a process of storing the data to some permanent medium and retrieving it back at any point of time. Hibernate implements JPA (Java persistence API).

Why ORM is required?


Let say we have to save the data from our Employee object to DB. Traditional way is to send data in SQL queries through JDBC. The problem here is this, we have objects in Java but not in DB. Objects are individual entity that needs to converted/mapped  to DB by using some code. This mapping is time consuming and often repetitive. Similar case for reading. We have to convert result-set to Java objects.

Problems with the traditional approach:

  • Mapping columns from DB to member variables in java
  • Mapping relationships – Suppose , we have separate address table with foreign key mapped to Employee primary key.  This relational thing in DB is not properly mapped to the java object side. People tend to compromise this at object side of it.
  •  Handling data types- eg. we have a Boolean in our data type in objects, but most DB have no Boolean variable, we would use Y/N or 0/1
  • Managing changes to object state


  • Improved productivity – Less java code to write with no SQL to write.
  • Imroved performance – Caching, lazy loading, eager loading.
  • Improved maintainability – less code to manage.
  • Improved portability – If you decides to change DB, less changes needs to be done.

The following gives a overview of hibernate architecture.



Download the latest version from here.

Extract the zip file. Go to the lib folder and make a note of all the jars under ‘jpa‘ and ‘required‘ folder. These are the jars that we need to include in our eclipse project. Right now the version I am downloading is 4.3.1.

Create a Java project. Add all the above hibernate dependencies jar. Depending on what DB we are configuring with hibernate we have to supply the JDBC driver. I am using MySQL, so I have added mysql-connector-java-5.1.28-bin.jar.

Create a file called ‘hibernate.cfg.xml‘ in your src folder of your java project. This is the default name for the hibernate configuration file. If we stick to it, we do not have to give any name to hibernate, but we are using different hibernate file, we have to pass the file name. We can pull up some config files that has come up with the download.  Check the project folder having db details.


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD//EN"
 <!-- Database connection settings -->
 <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
 <property name="connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">admin</property>
 <!-- JDBC connection pool (use the built-in) -->
 <property name="connection.pool_size">1</property>
 <!-- SQL dialect -->
 <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 <!-- Disable the second-level cache -->
 <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
 <!-- Echo all executed SQL to stdout -->
 <property name="show_sql">true</property>
 <!-- Drop and re-create the database schema on startup -->
 <property name="hbm2ddl.auto">create</property>
 <!-- Names the annotated entity class -->
 <mapping class="com.hibernate.dto.Employee"></mapping>

Lets get into brief details on some of the properties here:

connection.driver_class : This will be the driver class depending upon your DB. Here I am using MySQL driver.

connection.url : Again this will change according to your DB. Here ‘hibernatedb’ at the end in the URL is the name of my schema. Will surely be different for yours.

dialect : Again depends on the DB you are using.Dialect is a configuration so that hibernate knows what lang to talk to DB. SQL is base , but SQL queries is little bit different in oracle or MySQL etc. I am using MySQL dialect. You can google dialect according your DB, like for oracle 10g its org.hibernate.dialect.Oracle10gDialect.

show_sql : If true, hibernate will print out all the sql it runs

hbm2ddl.auto : Depending on what the modal object, hibernate will create the DB schema/table etc  if its not there in DB.

mapping class : is the class we want hibernate to persist. Following is my Employee class:

package com.hibernate.dto;

import javax.persistence.Entity;
import javax.persistence.Id;

public class Employee {

 private int id;
 private String name;
 public int getId() {
 return id;
 public void setId(int id) {
 this.id = id;
 public String getName() {
 return name;
 public void setName(String name) {
 this.name = name;


Notice that we have given clues to hibernate as to how to persist the class using annotation. We can do the same by xml, but lets use annotation for now.

@Entity = It needs to treat this class as entity and it needs to save it. We have already given this in hibernate.cfg.xml but still we have to give it using annotation.

@Id = Tells hibernate to treat it as primary key

Lets make our test class:

package com.hibernate.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.hibernate.dto.Employee;

public class HibernateTest {

 public static void main(String[] args) {
 Employee user=new Employee();
 user.setName("First User");
 SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
 System.out.println("session factory created");
 Session session=sessionFactory.openSession();


Run – This will create a table ’employee’ in your schema if already not present there, and insert one row in it. Please check the table on DB side and note the column names made.

Other important points to keep in mind:

Check that hibernate.cfg.xml is always on the root path. If its is a package, make sure we have to give in SessionFactory sessionFactory=new Configuration().configure(“your path”).buildSessionFactory();

Run java main class again with by changing object values. Check in DB. You will see that previous data has been deleted and new inserted. The reason for this to be happing is because of the following config

<property name=“hbm2ddl.auto”>create</property>

This means hibernate will Drop and re-create the database schema on startup. To retain data change it to ‘update’. Now hibernate will only make the change if its find the change in Modal.

Grab the code from my GitHub repository.

In the next part we will build over this. See you then..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: