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

dependencies

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.

mapping

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"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="eg">

<class name="Cat"
table="cats"
discriminator-value="C">

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

<discriminator column="subclass"
type="character"/>

<property name="weight"/>

<property name="birthdate"
type="date"
not-null="true"
update="false"/>

<property name="color"
type="eg.types.ColorUserType"
not-null="true"
update="false"/>

<property name="sex"
not-null="true"
update="false"/>

<property name="litterId"
column="litterId"
update="false"/>

<many-to-one name="mother"
column="mother_id"
update="false"/>

<set name="kittens"
inverse="true"
order-by="litter_id">
<key column="mother_id"/>
<one-to-many class="Cat"/>
</set>

<subclass name="DomesticCat"
discriminator-value="D">

<property name="name"
type="string"/>

</subclass>

</class>

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

</hibernate-mapping>


configuration

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"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- 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"/>

</session-factory>

</hibernate-configuration>


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();
session.beginTransaction();

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

// The getEmailAddresses() might trigger a lazy load of the collection
aPerson.getEmailAddresses().add(emailAddress);

session.getTransaction().commit();



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

Geen opmerkingen:

Een reactie posten