NHibernate: Complex relationships
Join the DZone community and get the full member experience.
Join For Freei got an interesting question today (i am teaching my nhibernate course now).
the tabular structure is similar to this:
but the desired object structure is:
that is quite different than the tabular model, but it is actually very easy to handle this with nhibernate.
here are the mapping for the address entity. we use the <join/> tag to have an entity that spans more than a single table:
<class name="address"
table="addresses">
<id name="id">
<generator class="identity"/>
</id>
<property name="city" />
<join table="peopleaddresses" >
<key column="addressid"/>
<property name="isdefault"/>
<property name="validfrom"/>
<property name="validto"/>
</join>
</class>
we then map the person, using standard many-to-many mapping for the addresses:
<class name="person"
table="people">
<id name="id">
<generator class="identity"/>
</id>
<property name="name" />
<bag name="addresses" table="peopleaddresses" inverse="true">
<key column="personid"/>
<many-to-many class="address" column="addressid"/>
</bag>
</class>
there is just one thing thing to be aware of, you can’t add new addresses via the person.addresses collection, because the peopleaddresses table has more data in it than just the keys. presumably, you are handling this in some other fashion already.
all in all, this is a pretty elegant solution.
Published at DZone with permission of Oren Eini, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments