Tuesday, March 15, 2011

How to map a deeper hierarchy in nhibernate

I have this object graph, I want to map:

  • abstract Account (username, password, ...)
    • abstract Customer (shoppingcart, orders, roles)
      • IndividualCustomer (user data)
      • CorporateCustomer (different user data, company data)
    • Administrator (adminroles)

How can this be mapped against one table? (I know how to do this with an entity hierarchy that is only 1 level deep, just like in the docs, but this is different).

Anybody has an idea? I asked the same in http://groups.google.com/group/nhusers/browse_frm/thread/7a85cba0048c18d8?hl=en, but so far have not received a useful answer.

From stackoverflow
  • From what I see, it should be no different than one-level-deep hierarchy. try this:

    <hibernate-mapping> 
    <class                                                     
        name="Account" 
        table="..." > 
        <property .../> 
            ... 
        <subclass                                              
            name="Customer" > 
            <property ... "/> 
            ... 
        </subclass> 
    
        <subclass                                              
            name="IndividualCustomer" > 
            <property ... "/> 
            ... 
        </subclass> 
        ... 
    </class>
    

    I don't have NHibernate here, to check it, but it looks like it should work. You may also want to try to nest subclass elements if it doesn't.

  • hey krzysztof,

    nesting subclasses is against the xml schema, so my guess is, it will not work. i probably would also have to nest the discriminator declaration, which also seems hackish.

    and mapping it out flat... i pass a discriminator for an abstract class, that cannot ever be used because an abstract class cannot be instantiated. seems wrong, too.

    but you are right, i will try it out some time. right now it seems like a better idea to me to let customer have an account, instead of being one.

    thanks!

    Krzysztof Koźmic : true, composition over inheritance is almost always a good idea. However your question still remains valid for those really few cases when it's not.

0 comments:

Post a Comment