Strictly Programming

Getting started with Hibernate 3

Posted in Hibernate by sqllyw on 03/29/2008

This is a quick guide to get started with Hibernate 3(with xml) in 10 minutes.

Stateless Session/Batch Update/DML style operation:worth take a look when working with large dataset.

Derived/Calculated property using @Formula

It is easy to get started with Hibernate but I am sure many people spend more time in getting it up and running, it is usually due to the configuration, directory structure and location of those xml files, in this guide I will be very detailed in that aspect to make sure you spend only 10 minutes:)

I will assume you have finished reading Using Maven 2 to create a project and Maven project directory layout, logging.

Add first a

public class Message {
    private Long id;
    private String text;
    public Long getId() {
        return id;
    public void setId(Long id) { = id;
    public String getText() {
        return text;
    public void setText(String text) {
        this.text = text;
   	public Message(String text) {
        this.text = text;
    public Message() {

Map the above class to a database schema
To do the mapping you have to create a file with the same name as the class you are mapping to, file extension should be hbm.xml, in this example, it is Message.hbm.xml and save it under ‘resources’ directory:

<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?>
<!DOCTYPE hibernate-mapping PUBLIC
        &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
    <class name=&quot;; table=&quot;MESSAGES&quot;>
        <id name=&quot;id&quot; column=&quot;MESSAGE_ID&quot;>
            <generator class=&quot;increment&quot;/>
        <property name=&quot;text&quot; column=&quot;MESSAGE_TEXT&quot;/>

Get dependencies from maven repository
We will use HSQLDB as the database, also Hibernate as OR mapping framework, we need to specify the dependencies in the pom.xml, it’s kind of simple, just add following code into the dependency section in the pom.xml:


Hibernate Configuration and start up
We will create a hibernate.cfg.xml to specify the parameters including mapping to java classes, place this file under the resources directory of your project and outside of any package, after compilation it will be in the root of classpath(check target/classes/hibernate.cfg.xml after compilation):

you might have notice that the database name is test under the data directory, for that you have to create a directory right under my-test, in the same level as src directory:

Add following class to the mytest package

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;

It’s time to write some code to access the database, just update the with following code


import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

 * Hello world!
public class App 
    public static void main( String[] args )
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();

        Message message = new Message("Hello World!");;

        Message message2 = new Message("Hello Java!");;

        Session session2 = HibernateUtil.getSessionFactory().openSession();
        tx = session2.beginTransaction();

        List messages = session2.createQuery("from Message").list();

        for (Object o: messages) {
            Message m = (Message) o;


compile and run the program:

mvn clean
mvn compile
mvn exec:java	

you should see: Hello World! Hello Java!

Note about xml files
It is important to put the hibernate.cfg.xml and those *.hbm.xml files in the correct locations, example if we put hibernate.cfg.xml in the ‘resources’ directory, and *.hbm.xml under ‘resources/hbm’ then we have to update the cfg.xml to reflect the change:


HSQLDB connection strings

connect to a database named test under data direcotry, in process server is used.
This connects to a stand alone server with alias xdb, you can start the server:
java -cp ../lib/hsqldb.jar org.hsqldb.Server -database.0 file:mydb -dbname.0 xdb

Tagged with: , ,

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your 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: