Despite my interest in all things Ruby especially Ruby on Rails, I’ve decided to have a look at some powerful enterprise Java technologies. As you know, last semester, I taught Software Architecture at Masters level and I’ve become fond of using Java once more (which I used for the lab sessions).
Of course, the fact that Java is now opensource and so are most of the most interesting Java libraries and frameworks has also influenced me.
Anyway, today I’ve spent some time with Hibernate which is a framework to map plain old Java objects (POJOs) to relational databases. Basically, it allows a programmer to write a database application using normal object-oriented development methodologies and without writing a single line of SQL.
The first step is to write a POJO. It does not have to be a Javabean (Hibernate is perfectly happy if attributes don’t have getters and setters). For instance, this will do:
public class District {
private Integer id;
private String name;
public District() {
}
}
Then write a mapping file which is basically an XML which describes how each attribute will be stored in a relational database. In many cases, this is trivial:
<hibernate-mapping>
<class name="datasource.District" table="DISTRICTS">
<id name="id" column="DISTRICT_ID" access="field">
<generator class="native" />
</id>
<property name="name" column="NAME" access="field" />
</class>
</hibernate-mapping>
In case you have a many-to-one or a many-to-many association, have a look at chapter 7 of the Hibernate documentation. It’s explicit enough.
Configuring Hibernate to connect to your database is easy (I use MySQL 5.0 with the latest Connection/J JDBC driver). Just follow the official tutorial. The important part is:
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
Finally, write a small toy application in Java to force Hibernate to create the database schema:
package hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class CreateDatabaseSchema {
public static void main(String[] args) {
Session session = null;
try {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session = sessionFactory.openSession();
session.flush();
session.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Tomorrow, I’ll use the Spring framework to decouple Hibernate from my application. I’ll surely indulge in some dependency injection. Yummy!
(Muhammad Ali picture courtesy of this website)