If you work with Java and databases, you really have to check out Hibernate because it’s so well done and it’s transformative in what it enables in the application. It’s doing all the O-R persistence for my Java classes on a new project and I’m very happy with it. I’ve included a short sample that relies on XDoclet’s Hibernate tags to simplify the mapping file generation.

Most Hibernate tutorials have you start with the mapping files, but after looking around I decided the best way to go was to work from the Java source and put the metadata there in order to generate the mapping files automatically using XDoclet’s Hibernate support. You just add special javadoc comments like this:
/**
* @hibernate.class table=”sites”
*/
public class Site implements Serializable
{
private long id;
/**
* @hibernate.id generator-class=”native” unsaved-value=”0″
* @return
*/
public long getId()
{
return id;
}
And then run a generate Ant task that creates this:
<hibernate-mapping>
<class
name=”model.Site”
table=”sites”
dynamic-update=”false”
dynamic-insert=”false”
>
<id
name=”id”
column=”id”
type=”long”
unsaved-value=”0″
>
<generator class=”native”>
</generator>
</id>
…
And then in my Java code, after initializing Hibernate, I can do this:
Site site = new Site();
site.setName(“Test Site 1″);
session.save(site);
Or retrieve it like this:
site = session.load(Site.class, id);
And the full graph of objects is handled for you (either immediately or lazily), with tremendous control and flexibility — almost too much. There are many options and even with the terrific documentation it’s sometimes hard to figure out what the right combinations are.
A note on collection mappings: For now, I’ve been relying mostly on Lists for my collection types, mapped to Bags in Hibernate, using an inverse relationship from the parent and having the child do the many-to-one. This has the effect of requiring a bi-directional link between the two, and I’m sure there’s a better way to do this but I haven’t gotten there yet.