woensdag 11 juli 2007

hibernate: once set up you'll love it

Hibernate is lovely... it needs a little more attention to set up but once that's done no other persistence framework will beat it. So let's go over the setup steps here. I know there is a lot of information (good job on that from hibernate, springs lacks this at the moment) on this topic online, still it would be nice to have an overview (so I can get back to this summary myself).


Let it be clear that using hibernate means you'll need to add some dependencies, jar files, to your project. If you use maven to manage these depencies this can't be hard.

your model

You'll need some POJO's or Plain Old Java Objects you want to store. These are simple Java objects with a ctor, some private properties and public setters and getters, also called JavaBeans.


Next you need to let hibernate know how these POJO's need to be stored in whatever JDBC enabled db you want to use. Therefore create a mapping file for all your POJO's. I use the following one as a reference, it comes from the hibernate reference documentation (see sources). Also make sure you check the mapping cheat sheet (sources) for more advanced mapping files.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping package="eg">

<class name="Cat"

<id name="id">
<generator class="native"/>

<discriminator column="subclass"

<property name="weight"/>

<property name="birthdate"

<property name="color"

<property name="sex"

<property name="litterId"

<many-to-one name="mother"

<set name="kittens"
<key column="mother_id"/>
<one-to-many class="Cat"/>

<subclass name="DomesticCat"

<property name="name"



<class name="Dog">
<!-- mapping for Dog could go here -->



Then you can already configure hibernate. Create an xml file called hibernat.cfg.xml in your project resources folder and copy the following, adjusted for your needs, into it.

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"



<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:hsql://localhost</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</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>

<mapping resource="events/Event.hbm.xml"/>



Check the hibernate reference documentation (sources) for more information on this config. Good to know is that the jdbc driver and sql dialect depend on the database you are using. Als the mapping resources at the bottom here need to point towards your mapping files you created earlier.

some util

You can use the following util code to access the hibernate session.

package util;

import org.hibernate.*;
import org.hibernate.cfg.*;

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;


hit it

Now you can start writing your services. In these services you retrieve the hibernate session, begin and commit transactions and in between this you'll saveOrUpdate, load, delete, list, ... your POJO's. For more specific queries you'll need to get into hql.

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

Person aPerson = (Person) session.load(Person.class, personId);

// The getEmailAddresses() might trigger a lazy load of the collection


o hibernate reference documentation
o hibernate mapping cheat sheet
o hibernate tutorial, quick start

Geen opmerkingen:

Een reactie plaatsen