Hibernate Basics

Hibernate is an open source ORM (Object Relational Mapping) framework helps to move from object oriented programming to relational databases. For a beginner in Hibernate , this  page will provide a quick overview about the different concepts in  Hibernate.


It is a threadsafe (immutable) cache of compiled mappings for a single database and also it is a factory for Session. SessionFactory is too expensive to create.


Session is a conversation between the application and the persistent store representing as a single threaded, short lived object. It covers a JDBC connection. It acts as a factory for transaction. It handle mandatory or first level cache of persistent objects when migrating the object graph or looking up objects by identifier.

Hibernate Basics
Hibernate Basics

Persistent objects and collections

It’s a short lived, single threaded objects consists of persistent state and business function and includes JavaBeans/POJOs. The speciality persistent object is they are currently associated with exactly one Session. They will be detached and free to use in any application layer as soon as the Session is closed.

E.g.:- Direct data transfer of objects to and from presentation.

Transient objects and collections

Instances of persistent classes that is not currently associated with a Session. They may have been instantiated by the application and not (yet) persisted or they may have been instantiated by a closed Session.


Transactio is a single-threaded, short-lived object used by the application to specify atomic units of work.  It abstracts application from underlying JDBC, JTA or CORBA transaction. It provide multiple transactions per session.


It is a factory for (and pool of) JDBC connections. It helps to abstracts application from underlying Datasource or DriverManager. It never exposed to application, but can be extended/implemented by the developer.


It’s a factory for Transaction instances and never exposed to the application, but can be extended /implemented by the developer.

Hibernate Architecture

Hibernate is an open source ORM (Object Relational Mapping) framework helps to move from object oriented programming to relational databases.  It provides several object oriented concepts like Association, Polymorphism, Inheritance and Composition through persistent classes and also provide some hibernate facilities such as write queries in variant forms, HQL (Hibernate Query Language), Native SQL, or Criteria API.  JDBC API’s are easy to use for small projects. But Hibernate framework is well suited for enterprise level applications and acts as mediator between object & relational approaches.

These are the operations that can be handled by Hibernate

1)      Opens a database connection

2)      Converts HQL statements to database specific statements

3)      Execute it and receive data from the database

4)      Result set being mapped to equivalent java objects to be processed by application.

Hibernate Architecture
Hibernate Architecture

In the above figure the XML Mapping provide the mechanism of Database Schema Generation and Java Code Generation.

Database Schema Generation



Java Code Generation


Eg: – BookApps

The above application uses a PostgreSQL database and it helps to run an instance of PostgreSQL.

Hibernate configuration file: – hibernate.cfg.xml

The above file helps to connect Hibernate to a database. Here we are using PostgreSQL database.  Hibernate configurations can done through hibernate.properties file.


<!--<span class="hiddenSpellError" pre=""-->
DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<a href="http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"</a>>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.username">postgres</property>
<property name="connection.password">******</property>
<!-- SQL dialect - generate SQL for a particular database -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Echo all executed SQL statements -->
<property name="show_sql">true</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Mapping resource configuration files -->
<mapping resource="src/com/bookstore/bookapp.hbm.xml"/>

Hibernate mapping file: – bookapp.hbm.xml

Hibernate needs this XML file, for all objects to be persisted in the database. This mapping file tells how to load and store all objects, which tables accessed and which columns are used in the table. This file should be saved with .hbm.xml file extension.

<?xml version="1.0"?>
<!--<span pre=""-->DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<a href="http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"</a>>
<hibernate-mapping package="com.bookstore">
BookDetails" table="BookStore">
bookName" column="BookName"/>
authorName" column="AuthorName"/>
bookCost" column="BookCost"/>

Persistent class: –  BookDetails.java

The working of persistent class is in the form of POJO (Plan Old Java Object) model. It’s a java bean class having getter and setter methods to access the properties of an app.

package com.bookstore;
public class BookDetails{
private int bookId;
private String bookName;
private String authorName;
private int bookCost;
BookDetails(){            }
public int getBookId(){
return bookId; }
public void setBookId(int bookId){
this.bookId = bookId; }
public String getBookName(){
return bookName;       }
public void setBookName(String bookName){
this.bookName = bookName; }
public String getAuthorName(){
return authorName;     }
public void setAuthorName(String authorName){
this.authorName = authorName;}
public int getBookCost(){
return bookCost;
public void setBookCost(int bookCost){
this.bookCost = bookCost;     }
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append("BookName : ").append(bookName);
sb.append(" ,AuthorName : ").append(authorName);
sb.append(" , BookCost : ").append(bookCost);
return sb.toString();

Hibernate communication with database: – Hibernate Util.java

Load the hibernate configuration file and mapping files automatically, create a session factory from the configured object, create a session to execute the HQL query and get the result set of java objects.

package com.bookstore;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
}  catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}          }
public static SessionFactory getSessionFactory() {
return sessionFactory;
} }

Application class: –  BookApp.java

It is a simple application class which performs CRUD operations in the database through HQL, Persistent Objects, Native SQL and Criteria API.

package com.bookstore;
import java.util.List;
import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
public class BookApp{
public static void main(String args[]){
BookMethods bm = new BookMethods();
//Adding books
bm.addBook("Professional Hibernate","Eric Pugh, Gradecki", 350);
bm.addBook("Hibernate in Action","Christian Bauer, Gavin King", 499);
bm.addBook("Java Persistence With Hibernate","Bauer, Gavin King", 423);
bm.addBook("Begining Hibernate","Dave Minter, Jeff Linwood", 1500);
//Listing added books
//Getting book details for a particular book name.
bm.getBookDetails("Hibernate in Action");
//To see no. of books
//Update particular book cost
bm.updateBook("Begining Hibernate",1000);
//Listing available books
//Deleting a book
bm.deleteBook("Java Persistence With Hibernate");
//Listing available books After executing delete
} }
class BookMethods{
//Using persistent objects to store data into the database.
public void addBook(String bookName, String authorName, int bookCost){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
BookDetails bd = new BookDetails();
session.getTransaction().commit();     }
//Using persistence object to delete a row from the database.
public void deleteBook(String bookName){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
List list = session.createQuery("from BookDetails where bookName='"+bookName+"'").list();
Iterator itr = list.iterator();
BookDetails bd = (BookDetails)itr.next();
System.out.println("delete : "+bd);
session.delete(bd);      }
session.getTransaction().commit();     }
//Using Criteria API to update the book cost
public void updateBook(String bookName, int bookCost){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Criteria cri = session.createCriteria(BookDetails.class);
cri = cri.add(Restrictions.eq("bookName", bookName));
List list = cri.list();
BookDetails bd = (BookDetails)list.iterator().next();
session.getTransaction().commit();     }
//Using HQL - Hibernate Query Language
public void getBookDetails(String bookName) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Query q = session.createQuery("from BookDetails where bookName=:bn");
q.setString("bn", bookName);
List list = q.list();
System.out.println("Getting Book Details using HQL. \n"+list);
//The above query can also be achieved with Criteria & Restrictions API.
Criteria cri = session.createCriteria(BookDetails.class);
cri = cri.add(Restrictions.eq("bookName", bookName));
list = cri.list();
System.out.println("Getting Book Details using Criteria API. \n"+list);
//Aggregate function.
public void countBook() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
List list = session.createQuery("select count(*) from BookDetails").list();
System.out.println("Aggregate function count \n"+list);
session.getTransaction().commit();     }
//Native SQL Query
public void listBooks() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
List list = session.createSQLQuery("select * from  BookStore").addEntity(BookDetails.class).list();
Iterator itr = list.iterator();
while(itr.hasNext()) {
BookDetails bd = (BookDetails)itr.next();
System.out.println(bd);           }
}          }

Compile & Run the simple application: BookApp.

Setting classpath

Following jars are required to compile and run the code. Copy the below code and save it in a file called classpath.bat & run this batch file.

set HIBERNATE_HOME=C:\Hibernate\hibernate-distribution-3.6.0.Final

set CLASSPATH=%HIBERNATE_HOME%\hibernate3.jar;%HIBERNATE_HOME%\lib\required\dom4j-1.6.1.jar;%HIBERNATE_HOME%\lib\required\slf4j-api-1.6.1.jar;%HIBERNATE_HOME%\lib\jpa\hibernate-jpa-2.0-api-1.0.0.Final.jar;%HIBERNATE_HOME%\lib\required\commons-collections-3.1.jar;%HIBERNATE_HOME%\lib\required\javassist-3.12.0.GA.jar;%HIBERNATE_HOME%\lib\required\jta-1.1.jar;%HIBERNATE_HOME%\lib\required\antlr-2.7.6.jar;.;C:\PostgreSQL\postgresql-9.0-801.jdbc3.jar

Compile all the java files

C:\Hibernate\hibernate-distribution-3.6.0.Final\example\booksapp>javac -d . src\com\bookstore\*.java

Run the app

C:\Hibernate\hibernate-distribution-3.6.0.Final\example\booksapp>java com.bookstore.BookApp


By going through this page as beginner you should have grasped the basics of hibernate. You can refer other sections about hibernate in this site to learn more.