Quick Hibernate

As per http://www.hibernate.org, Hibernate is a powerful, ultra-high performance object/relational persistence and query service for Java. Hibernate gives you the option to code and work with Java and use Hibernate’s capabilities to interact with the database. No need to write SQL in your Java code. You work with Java objects and Hibernate does the rest.

In this “Quick Hibernate” series of articles, Satish Talim gets you started with Hibernate. Satish’s hands-on approach should have you developing with Hibernate in no time.

Also check out Satish’s interview: Java and J2EE Today

By Satish Talim

We need a means of taking information from a
SQL database and turn it into Java objects, and vice-versa. The general problem is known as Object/Relational Mapping. Hibernate is a
lightweight O/R mapping service for Java and gives you the
persisting your Java objects to and from an underlying database. Rather
than you writing the SQL and converting queries to and from first class
objects, Hibernate can take care of all this for you. You only concern
yourself with the objects, Hibernate worries about the SQL and making
sure things end up in the right tables.

are many books and articles available on Hibernate and what I want to
do here is quickly get you started with Hibernate. I want to take this
opportunity to thank Glen Smith for showing me the
quick way to get started with Hibernate and this blog is based on that
and dedicated to him.

Quick Installation and

  • Install J2SDK 1.4.2
  • Install Ant
  • Go to http://www.hibernate.org/
    and download Hibernate
  • Install
    Hibernate by unzipping the
    file hibernate-2.1.6.zip to drive
    say F:

  • Setup a Project Hierarchy by doing the following  Create folder
    F:hlogin and then create
    sub-folders F:hloginsrc and F:hloginlib
  • Copy all the contents of F:hibernate-2.1lib to
  • Copy hibernate2.jar to F:hloginlib
  • The
    example classes we are going to create are all going to reside in
    the folder F:hloginsrccomtalimdemo. Create these sub-folders.

Quick Compile


To quickly compile your Java code:


At the folder F:hlogin
type ant

To run your Hibernate programs

At the folder F:hlogin
type ant run

>> Resource: Build.xml

The Development Process


are several ways to approach Hibernate development. Here’s the one that
is probably the most straightforward to understand:

  • Create your SQL
    table to hold your persistent objects
  • Create a Java bean
    that will represent that object in code
  • Create a mapping
    file that Hibernate knows which bean properties map to which SQL fields
  • Create a
    properties file so Hibernate knows your JDBC settings to get to the
  • Start using the
    Hibernate API

you get more proficient, there are tools to help auto-generate either
Beans from SQL or SQL from Beans (and even plug-ins to make the mapping
file for you), but let’s do it the long way first, so you don’t get distracted.

Step 1: Create the table


The example we’re working through is a very
simple one. Lets say you need a users table (in say database jboss).

myusers (

varchar(20) NOT NULL default ‘0’,

Name varchar(40)
default NULL,

varchar(20) default NULL,

varchar(40) default NULL,

LastLogon datetime
default NULL,



are using mySql, but you can use any database that you have a JDBC
driver for. We’ve got a User table with a Logon ID, Full Name,
Password, Email and date of last logon. Next step is to write a Java
bean to handle a given User

Step 2: Write the Bean

Hibernate works via reflection on get/set
methods of the objects
, so we’ll need to create the objects (as
beans) we want to persist.

import java.util.Date;
import java.io.Serializable;

public class
MyUsers implements Serializable
private String userID;
private String userName;
private String password;
private String emailAddress;
private Date lastLogon;

public MyUsers()

public String
return userID;

public void
setID(String userID)
this.userID = userID;

public String
return userName;

public void
setUserName(String userName)
this.userName = userName;

public String
return password;

public void
setPassword(String password)
this.password = password;

public String
return emailAddress;

public void
setEmailAddress(String emailAddress)
this.emailAddress = emailAddress;

public Date
return lastLogon;

public void
setLastLogon(Date lastLogon)
this.lastLogon = lastLogon;

In our example above,
we’ve made the accessors (getID(), getLastLogon(), etc) public – but
that’s not a requirement for Hibernate – it can use public, protected
or even private methods to persist your data.

Step 3: Writing the Mapping File

we’ve now got our SQL table, and the Java object that’s going to map to
it. We still need a way to tell Hibernate how to map from one to the
other. This is accomplished via a mapping file. Hibernate uses an
XMl document to track the mapping between Java classes and relational
database tables


cleanest (most maintainable) way is to write one mapping file per
object, and if you name it YourObject.hbm.xml and put it in the same
directory (F:hloginsrccomtalimdemo)as your real object, Hibernate will
make things even easier for you
Here’s an example of what MyUsers.hbm.xml
might look like:

Resource: MyUsers.hbm.xml

Let’s have a look at
some lines of interest in our file. The first tag of interest is the
class tag. Here we map from the class name to the users table in our
database. Let’s skip the ID tag for a moment and talk about the
property tags. A cursory scan will show this is where the work is being
done. The name attribute is the property on our Java bean, and the
column is the name of the field in our database. The type attribute is
optional (Hibernate will use reflection for a best-guess if you leave
it out) – but I’ve put it in here for completeness.


Let’s return to that ID tag. You may have guessed that this tag has
something to do with mapping to the primary key of the table. You’d be
right. The form of the ID tag is very similar to the property tags we
just looked at. We map from the bean property (name) to the target
database field (column).



embedded generator tag tells Hibernate how it should produce the
primary key (it’s quite happy to generate one for you, of whatever type
you prefer, but you’ll need to tell it how). In our case, we set it to
assigned, meaning that our bean is going to generate its own keys (the
User object will always need to have a UserID after all).


Step 4: Creating a Properties File for Your

still haven’t told Hibernate where to find our database. The most
straightforward way is to feed Hibernate a properties object, with
settings for the connection strings, passwords, etc. If you name this
file hibernate.properties, copy it to folder

F:hloginsrc and put
it in your classpath
, Hibernate will pick it up automatically.
Here’s what it looks like:







example above uses a mysql driver, connects to the jboss database on, and uses the supplied username and password. There are a
bunch of other properties you can set to “tune” how Hibernate accesses
your database of choice. Once again, checkout the document for detailed

alternative approach is to specify a full configuration in a file named
This file can be used as a replacement for the hibernate.properties
file or, if both are present, override properties. The XML
configuration file is by default expected to be in the root of your

Step 5: Start using the Hibernate API

If all has gone well so far, you’ll have the


  • A SQL User table in your database
  • MyUsers.java – your Java bean object to
  • MyUsers.hbm.xml – your Hibernate mapping file
  • hibernate.properties – your properties file
    with JDBC connection info

Making use of Hibernate
in your source is pretty straightforward.

  • Create a Configuration object
  • Tell the
    Configuration about the type of objects you want to map
  • Create a Session to your database of choice
  • Load, Save and Query your objects
  • flush() your Session back to the database

Steps 1 and 2


The Configuration object is based on the
properties file, we have put in the standard place



config = new Configuration();




assumes you’ve got a MyUsers.hbm.xml file in the same directory as your
user class. If you decided to call your file something else, use


Step 3

Session object represents a connection to your backend database. You
can feed Hibernate a JDBC session that you’ve created by hand, but I’m
lazy, so I’m just going to feed Hibernate the properties file with my
settings, and let it do the work for me.

// Then build a
session to the database

sf = config.buildSessionFactory(); // or supply a Properties arg

Session session =

called my properties file hibernate.properties and put it in my
classpath, but if you’ve called yours something different (or you want
to create the Properties in code), then you’ll need to feed your own
Properties object to buildSessionFactory().

Step 4

Now you just use your objects in a
Java-native way. Would you like to store a new User in the database?
Try something like this:

// Create new User and store
them the database
MyUsers newUser = new MyUsers();
newUser.setUserName(“Satish Talim”);

newUser.setLastLogon(new Date());
// And the Hibernate call which stores it

As you can see, the great thing about
Hibernate is the low overhead. For the most part you just worry about
your business objects, and make a single call to Hibernate when you’re


so often your Hibernate Session object will flush itself to the
database to make the database is in sync with your memory copies of
objects. You’ll want to free up the JDBC connection that Hibernate’s
using, so you’ll typically shut down with:

// close our session and
release resources



// NB: some non-MySQL (Sybase,
etc) database users also need to…


on your JDBC driver, you’ll need to commit the underlying connection
too. You don’t need this if you’re using mySQL, but on other
transactional databases (like Sybase), you need an extra statement
after the close calling session.connection().commit()).


Heres the code for inserting a record in our
table MyUsers


import net.sf.hibernate.cfg.Configuration;

import java.util.Date;

class MyUsersTest
public static void main(String[] args) throws Exception
// Create a configuration based on the properties file we
// have put in the standard place
Configuration config = new Configuration();

// Tell it about the classes we want mapped, taking advantage
// of the way we have named their mapping documents

// A SessionFactory is Hibernate’s concept of a single datastore
// Get the sesion factory we can use for persistence
SessionFactory sessionFactory = config.buildSessionFactory();

// Hibernate’s Session, is the persistence manager interface,
// we use it to store and retrieve MyUsers to and from the database
// Ask for a session using the JDBC information we have configured
Session session = sessionFactory.openSession();

// Store a new User in the database
MyUsers newUser = new MyUsers();
newUser.setUserName(“Satish Talim”);
newUser.setLastLogon(new Date());

// And the Hibernate call which stores it
// close our session and release resources

// Clean up after ourselves

Well that’s it for now. Feedback on this blog is most

The author maintain his own technical blog, Appliblog
at http://personalwebsiteblog.blogspot.com


Content Team

The IndicThreads Content Team posts news about the latest and greatest in software development as well as content from IndicThreads' conferences and events. Track us social media @IndicThreads. Stay tuned!

21 thoughts on “Quick Hibernate

  • February 18, 2007 at 3:45 pm

    Hi Talim,
    The meaning of Talim in Urdu Language in India is education and you deserve to be having this as last name, good work keep up…….

    angel from USA

  • September 13, 2006 at 11:24 am

    when should we use Hibernate and when should we use EJB?

  • August 21, 2006 at 10:43 pm

    Its Short and Sweet information to the hibernate users

  • June 13, 2006 at 9:13 am

    good article for a person who is new to Hibernate… will get to know wht hibernate is about

  • May 29, 2006 at 8:19 am

    Hi This Article is Very Good for the Naive to learn Hibernate.
    Its Fine

  • August 19, 2005 at 2:16 am

    When compiling the files against Hibernate3 the package structure should be
    import org.hibernate.*;
    import org.hibernate.cfg.Configuration;

  • June 10, 2005 at 11:03 pm

    Also note that you can wrap the code in:
    Transaction txn = session.beginTransaction();
    … your db related code

    If you’d prefer. That’s a decent practice even when using something like MySQL.

  • May 6, 2005 at 12:37 am

    Chavalllll tienes que poner el


    para que furule !!!!! (despu?s de 2 horas dandole vueltas))

    Put the session.connection().commit(); to run correctly… (que lo entienda el que quiera))

  • April 27, 2005 at 5:30 pm

    This is really good article to quickly get on started with Hibernate. I have tried it with oracle and hibernate-3.0. I am really happy to see it working.
    Give it a try, it is worth going through the tutorial 🙂

  • December 23, 2004 at 5:37 am

    Yes, you can do that in Hibernate using Middlegen, or the new eclipse reverse engineering plugin.

  • November 17, 2004 at 12:28 am

    Kodo JDO provides a reversemappingtool, that you point to the schema and it generation OR mapping for you and creates all Java Beans, can one do that in hybernate? As writing all the beans and mapping could be as error prone as writing SQL.

    –Alexey Krasnoriadtsev

  • October 29, 2004 at 9:18 am

    Yes, you are right. I struggled a lot with the layout here.

  • October 26, 2004 at 10:55 am

    Observe the MyUsers.java (part code) file –
    public String getID()
    return userID;

    Look at the MyUsers.hbm.xml (part code) file –

    id name=’ID’ column=’LogonId’ type=’string’

    The ID tag has to do with mapping to the primary key of the table.
    Hope this clarifies things.

  • October 26, 2004 at 2:47 am

    Nice article.
    A rookie question though. The table has LogonID and the object has variable userID.
    Since as per article, if reflection is being used, won’t the mapping of LogonID fail ?


  • October 19, 2004 at 8:46 pm

    I am having quite the success using hibernate in my projects. This is a tool having a high success rate. I will encourage any of you to use Hibernate, since it is being used more and more.

  • October 19, 2004 at 4:21 pm

    I surely hope that there are more such articles on various J2EE topics. Very useful.

Leave a Reply