NHibernate: Complex relationships

DZone 's Guide to

NHibernate: Complex relationships

· Database Zone ·
Free Resource

I 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"
<id name="Id">
<generator class="identity"/>
<property name="City" />

<join table="PeopleAddresses" >
<key column="AddressId"/>
<property name="IsDefault"/>
<property name="ValidFrom"/>
<property name="ValidTo"/>


We then map the Person, using standard many-to-many mapping for the addresses:

 <class name="Person"

<id name="Id">
<generator class="identity"/>
<property name="Name" />

<bag name="Addresses" table="PeopleAddresses" inverse="true">
<key column="PersonId"/>
<many-to-many class="Address" column="AddressId"/>


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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}