A tough NH inheritance example

We have an inheritance tree like this:


Each class has a mapping table in database, one thing we (or our DBA) did wrongly is that both Inidividual and Organization tables have their own timestamp fileds. This caused a big problem when we were tring to follow the per-table-per-inheritance mapping example from NHibernate in Action book. Eventually, we had to treat those common fields from BaseStakeholder as a component like part in separated Individual and Organization mapping files, using the join syntax:

<class name=Individual table=Individual_CV >
id name=Id column=Stakeholder_ID unsaved-value=0 >
generator class=identity />
timestamp column=S_Datename=LastModifiedDategenerated=alwaysunsaved-alue=undefined/>

<property column=Gender type=string name=Gender not-null=true />

<bag name=Emailsaccess=field.camelcase-underscorelazy=truecascade =all-delete-orphan
key column=Stakeholder_ID foreign-key=Stakeholder_ID />
one-to-many class=Email />

<join table=Stakeholder_CV >
key column=Stakeholder_ID />
property column=Stakeholder_Type type=String name=StakeholderType not-null=true length=50 />
property column=Expired type=String name=Expired not-null=true length=3 />
property column=Last_Approval_Date type=DateTime name=LastApprovalDate not-null=true />

Duplication is unavoidable, until we move to Fluent NHibernate.

There is another trick in this inheritance mapping. We want to do bidirectional one-to-many mapping due to the not-null foreign key policy in our database, that’s why we set inverse=trueto Email property. But in Email.hbm.mapping, how can we map back to right type of stakeholder, instead of the virtual/abstract BaseStakeholder? Any keyword does the trick, but we need to move the StakeholderType field into email table/view to meet the requirements.

<class name=Email table=Stakeholder_Email_CV >

<any name=Stakeholder id-type=System.Int64 meta-type=System.String>
meta-value class=Individual value=Individual/>
meta-value class=Organization value=Organization/>
column name=Stakeholder_Type/>
column name=Stakeholder_Id/>

Again, this mapping part has to be duplicated in every mapping files of child class, like phone number, address, etc. How can FluentNHiberate also fix this issue?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s