OIC
Lemme take a stab. We'll implement a bidirectional one-to-many associations using Sets.
Mappings:
Code:
<hibernate-mapping>
<class name="eg.Thing">
<id name="thingId" type="java.lang.Long">
<column name="id"/>
<generator class="assigned" />
</id>
<property name="name" type="string">
<column name="name"/>
</property>
<property name="createDate" type="date">
<column name="cre_d"/>
</property>
<many-to-one name="thingHolder" class="eg.ThingHolder">
<column name="thing_holder_id"/>
</many-to-one>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="eg.ThingHolder">
<id name="thingHolderId" type="java.lang.Long">
<column name="thing_holder_id"/>
<generator class="assigned" />
</id>
<property name="name" type="string">
<column name="name"/>
</property>
<property name="createDate" type="date">
<column name="cre_d"/>
</property>
<set name="things" inverse="true">
<key>
<column name="id"/>
</key>
<one-to-many class="eg.Thing"/>
</set>
</class>
</hibernate-mapping>
And the
POJOsCode:
public class Thing {
private Long thingId;
private String name;
private Date createDate;
private eg.ThingHolder thingHolder;
// Getters and setters omitted for clarity
}
public class ThingHolder {
private Long thingHolderId;
private String name;
private Set things = new HashSet();
// Getters and setters omitted for clarity
// With bidirection associations, some collection management routines are highly suggested
// for example:
public void addThing(Thing thing) {
this.getThings.add(thing);
thing.setThingHolder(this);
// null-safety and exception checking omitted for clarity
}
}
Finally, the
queriesCode:
// Things from thing_holder_id
session.createQuery("from Things as thing where thing.holder.id=?");
// There are many other ways of accomplishing this same query, this example uses implicit joining
// ThingHolder from id
session.createQuery("from ThingHolder as holder where holder.things.id=?");
// I'd never do it this way, preferring to load the Thing instance and navigating to the ThingHolder via the getThingHolder() method
Sorry for any typos, etc. I don't have an IDE at the moment.