Monday, July 21, 2008

HIbernate join tables or xref tables or cross reference tables or cross-reference tables

I just spent a bit of time figuring out how to do bidirectional one-to-many mappings that are associated with a join table / xref / cross reference / cross-reference (I'm spelling all of these out in the event that some other poor soul is searching those terms) and exist in separate schemas.

Its actually spelled out (not the separate schema part, but that's easy) on the hibernate site which shouldn't be surprising since its an excellent site.

There are two tricks to making this work :
  1. Map the children into the parent as a many-to-many, but set "unique='true'" in the mapping.
  2. Map the join table into the child object.

In my case this meant something along the lines of this in the parent :
<set name="children" table="XREF" schema="PARENT_SCHEMA"
lazy="false" inverse="true">
<key column="XREF_PARENT_ID" not-null="true" />
<many-to-many unique="true" column="XREF_CHILD_ID" class="com.jeremyrdavis.Child" />

And this in the child :
<join table="PARENT_SCHEMA.XREF" inverse="true" optional="true" >
<key column="XREF_CHILD_ID" not-null="true" />
<many-to-one name="group" column="XREF_PARENT_ID" not-null="true"></many-to-one>

Blogged with the Flock Browser

1 comment:

Scott White said...

Nice entry, this also worked almost verbatim with NHibernate, except NHibernate does not have a unique attribute.