We are having a problem with Inheritance mapping and I was wondering if anyone could help. (We are fairly new to NHibernate, so if we’ve done anything stupid I apologise in advance).
We are using NHibernate 1.2.0.Beta1.
We have a Party base class. This has several sub classes, e.g. Individual, Member, Owner etc.
The Party class has its own mapping class in which is specified a one-to-many relationship (which is bidirectional) to a Policy class.
So, so far we have a Party, a Party.Policies collection, and a Party.Policies[0].Party.
Each sub class is defined as a ‘joined-subclass’ (although we have also tried ‘subclass’ and get the same problem).
The problem seems to be a memory management one….
If we load a Party (the base type) the Party object is the same as the Party.Policies[0].Party object, i.e. they both point to the same object on the heap. (In case you were wondering, we don’t actually do this as an individual always has a type, but this was done as part of our investigations).
However, if we load an Individual object (one of the sub classes of Party), the Individual.Polices[0].Party has a pointer to a completely different object. This means that any changes to the Individual object are not reflected in the bidirectional property Individual.Policies[0].Party, despite the fact that they both loaded from the same record in the database.
This is obviously not ideal and means, as well as the issue of 2 versions of the same record in code, that, when the Individual is saved to the database, NHibernate tries to save the data to the Party table twice.
The only obvious solution seems to be to loop through the Individual object on loading it, and manually set the bidirectional property to point to the root.
I have included some condensed versions of our mapping files below – are we doing something obviously wrong? Is there a tag we need to set in the Party mapping file to indicate that Party is a base type?
Thanks in advance for your help,
Alex
Note: Each class (and subclass) mapping is in its own mapping file:
<class name="Party" table ="Party" dynamic-update="true">
<id name="PartyID" column="PartyID" unsaved-value="-1">
<generator class="identity" />
</id>
<property name="Title" column="Title"/>
< property name="FirstNames" column="FirstNames"/>
<property name="LastName" column="LastName"/>
. . .
<bag name="Policies" cascade="all-delete-orphan" generic="true" inverse="true">
<key column ="PartyID" />
<one-to-many class="MGM.QBS.DTO.PolicyDTO, MGM.QBS.DTO" />
</bag>
</class>
<joined-subclass name="Individual" table="individual" >
<key column="PartyID"/>
. . .
</joined-subclass>
<class name=" Policy " table="Policy" dynamic-update="true">
<id name="PolicyID" column="PolicyID" unsaved-value="-1">
<generator class="identity" />
</id>
<property name="PolicyNumber" column="PolicyNumber" />
. . .
<many-to-one name ="Party" class="Party" column="PartyID" cascade="all-delete-orphan" />
</class>
|