Tuesday, June 06, 2006

Hibernate: Types and Mapping to Database

After configuring your environment as described here, now you can create your types - Java classes that also double as table structures in the database. We'll work with a simple class, Person, that represents a person.
  1. Create the source Person.java. Add the private properties, and their respective getters and setters, bean style. For the preperty intended to become the primary key of the table, make its setter private. This class is jubz.practice.Person.java, for example.
  2. Create the mapping file, Person.hbm.xml. This maps the fields of the Person class to a table and columns in the database. The mapping file is saved at jubz\practice\Person.hbm.xml (same place as its class file is).
  3. Insert a config mapping in the hibernate.cfg.xml, [mapping resource="jubz/practice/Person.hbm.xml"/], just before the closing [/session-factory] tag. This tells Hibernate where to find the mapping file.
The mapping file (sample):
[?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]
[class name="jubz.practice.Person" table="PEOPLE"]
[id name="id" column="GUID"]
[generator class="native"/]
[/id]
[property name="age" type="int" column="AGE"/]
[property name="firstname" column="FIRSTNAME"/]
[property name="lastname" column="LASTNAME"/]
[/class]
[/hibernate-mapping]
The mapping file describes which class properties map to which columns in what table, and their types, if any. The GUID column in the PEOPLE table will be the primary key. If you do not specify a (database data) type, Hibernate uses defaults from the dialects. If you do not specify a column, the property name will be used. Beware of naming types the same as special database names, such as "data" and "value".

The HibernateUtil.java class = sets up the sessions:
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;
}
}

To create a Person record in the database (sample):
Session session = HibernateUtil.getSessionFactory().getCurrentSession(); // Create a session
session.beginTransaction(); // Open the transaction
Long id = (Long)session.save(p); // Save data to the database, obtain id generated
session.getTransaction().commit(); // Commit the data

To list the Persons in the database (sample):
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List people = session.createQuery("from Person").list();
session.getTransaction().commit();
for (int i = 0; i < people.size(); i++) {
Person p = (Person) people.get(i);
}