15
Feb
NHibernate composite-element mapping
A tip for mapping value objects that is sort of buried in the NHibernate documentation.
Please note that a composite element mapping doesn't support null-able properties if you're using a <set>. NHibernate has to use each columns value to identify a record when deleting objects (there is no separate primary key column in the composite element table), which is not possible with null values.
When you fail to follow this guidance you get orphaned records left in the database when you delete them from the collection. When I fail to read the documentation (again) I learn a good lesson about how important it is to read the documentation (again). =)
After properly implementing Equals() and GetHashCode() with cascade="all" the persistence (and deletion) is transparent.
Just set 'em all to not-null.
Here is an example mapping from CodeCampServer:
<set name="Sponsors" table="Sponsors" cascade="all"> <key column="ConferenceId" /> <composite-element class="Sponsor"> <property name="Level" not-null="true"/> <property name="Name" length="50" not-null="true"/> <property name="LogoUrl" length="260" not-null="true"/> <property name="Website" length="260" not-null="true"/> <nested-composite-element name="Contact" class="Contact"> <property name="FirstName" length="20" not-null="true"/> <property name="LastName" length="20" not-null="true"/> <property name="Email" length="60" not-null="true"/> </nested-composite-element> </composite-element> </set>
March 9th, 2008 at 3:32 am
Thanks to Hugh Brown, I fixed some issues with the post you linked to here… please read the follow-up at
http://musingmarc.blogspot.com/2008/03/sometimes-you-make-hash-of-things.html