Sunday, August 10, 2008

Subclasses and NHibernate

NHibernate (well really Hibernate) has three strategies of inheritance. The one I was most interested in was the 'table per class hierarchy' as I had a User class and an expanded UserEx sub class. Which UserEx is used in the system is dependent on configuration of the application; in my case I am loading different user sub classes depending on which forum that my application is establishing a bridge with.

Both classes map to the same table. Each UserEx class has it's own full mapping and only the appropriate mapping depending on the bridge chosen is loaded.

This seemed to be perfect for the 'table per class hierarchy' strategy. Only one problem, I had no discriminator columns nor any need for one as I was only going to have one sub class.

I got around this by declaring my classes as such:


class User
{
// user properties
}

class UserEx: User
{
// expanded user properties
}


And my mappings as such:


<class table="appr. table" name="User" value="null">
<id ... >
<discriminator-value formula="">"/>
// property mappings
</class>

<subclass name="UserEx" extends="User" value="">">
// property mappings
</subclass>


While this works like a charm, it would be nice if Hibernate/NHibernate would expand the 'table per class hierarchy' strategy to handle more gracefully this scenario.

1 comments:

  1. Cheers for that hint. I have several subclasses with no added properties, just additional API to help enforce usage of the base class. But NHibernate was not too happy in dealing with the subclasses :)

    ReplyDelete