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

Quick
Hibernate
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
means
for
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.

There
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
Setup

  • 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
    F:hloginlib
  • 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

?

There
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
    database
  • Start using the
    Hibernate API

As
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).

CREATE TABLE
myusers (

LogonID
varchar(20) NOT NULL default ‘0’,

Name varchar(40)
default NULL,

Password
varchar(20) default NULL,

EmailAddress
varchar(40) default NULL,

LastLogon datetime
default NULL,

PRIMARY KEY
(LogonID)

);

We
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.


package
com.talim.demo;
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
getID()
{
return userID;
}

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

public String
getUserName()
{
return userName;
}

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

public String
getPassword()
{
return password;
}

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

public String
getEmailAddress()
{
return emailAddress;
}

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

public Date
getLastLogon()
{
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

So
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
.

?

The
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.

?

Ok.
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).

?

?

The
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
Database

We
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:

?

hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect

hibernate.connection.driver_class=com.mysql.jdbc.Driver

hibernate.connection.url=jdbc:mysql://127.0.0.1:3306/jboss

hibernate.connection.username=

hibernate.connection.password=

The
example above uses a mysql driver, connects to the jboss database on
127.0.0.1, 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
information.

An
alternative approach is to specify a full configuration in a file named
hibernate.cfg.xml.
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
CLASSPATH.


Step 5: Start using the Hibernate API

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

?

  • A SQL User table in your database
  • MyUsers.java – your Java bean object to
    persist
  • 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

?

?

Configuration
config = new Configuration();

?

Config.addClass(MyUsers.class);

?

This
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
ds.storeFile(“MyMappingFile.hbm.xml”).

?

Step 3

The
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

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

Session session =
sf.openSession();

I’ve
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.setID(“satish_talim”);
newUser.setUserName(“Satish Talim”);
newUser.setPassword(“informex”);
newUser.setEmailAddress([email protected]);

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

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
done.

Step
5

Every
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

session.flush();

session.close();

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

//
session.connection().commit();

(Depending
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()).

Example

Heres the code for inserting a record in our
table MyUsers


package
com.talim.demo;

import
net.sf.hibernate.*;
import net.sf.hibernate.cfg.Configuration;

import
com.talim.demo.MyUsers;
import java.util.Date;

public
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
config.addClass(MyUsers.class);


// 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
try
{
MyUsers newUser = new MyUsers();
newUser.setID(“satish_talim”);
newUser.setUserName(“Satish Talim”);
newUser.setPassword(“informex”);
newUser.setEmailAddress(“
[email protected]“);
newUser.setLastLogon(new Date());


// And the Hibernate call which stores it
session.save(newUser);
}
finally
{
// close our session and release resources
session.flush();
session.close();
}


// Clean up after ourselves
sessionFactory.close();
}
}


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

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

Resources:

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
    Permalink

    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
    Permalink

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

  • August 21, 2006 at 10:43 pm
    Permalink

    Its Short and Sweet information to the hibernate users

  • June 13, 2006 at 9:13 am
    Permalink

    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
    Permalink

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

  • August 19, 2005 at 2:16 am
    Permalink

    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
    Permalink

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

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

  • May 6, 2005 at 12:37 am
    Permalink

    Chavalllll tienes que poner el

    session.connection().commit();

    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
    Permalink

    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
    Permalink

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

  • November 17, 2004 at 12:28 am
    Permalink

    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
    [EMAIL][email protected][/EMAIL]

  • October 29, 2004 at 9:18 am
    Permalink

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

  • October 26, 2004 at 10:55 am
    Permalink

    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
    Permalink

    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 ?

    Regards,
    Nikhil

  • October 19, 2004 at 8:46 pm
    Permalink

    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
    Permalink

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

Leave a Reply