开发者

Joining to a subclass of a Table per Class hierarchy in NHibernate

I'm using the table per subclass mapping inheritance in NHibernate. I have a parent Attribute table and a child AccountAttribute table. The child AccountAttribute table has another foreign key in it to a CustomerProfile table. The CustomerProfile table has a zero or more relationship to the AccountAttribute table; meaning I'll have a collection of AccountAttributes in my CustomerProfile class.

How do I map the CustomerProfile table to the AccountAttribute table in my NHibernate mapping so that the CustomerProfile class is hydrated with it's correct AccountAttributes?

Tables

Attribute: Attribute_Id (PK)

AccountAttribute: AccountAttribute_Id (PK); Attribute_Id (FK); CustomerProfile_Id (FK)

CustomerProfile: CustomerProfile_Id (PK)

Mapping for the Attribute/AccountAttribute hierarchy.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" >
  <class name="Attribute, CustomerProfile" lazy="false">

    <id name="Identifier" column="Attribute_Id" access="field.camelcase">
      <generator class="identity"/>
    </id>

    <joined-subclass name="AccountAttribute, CustomerProfile" table="AccountAttribute" lazy="false">
      <key column="Attribute_Id" />
      <property name="Val开发者_如何学GoueText" column="Value_Txt" access="nosetter.camelcase" />
    </joined-subclass>

  </class>
</hibernate-mapping>

Mapping for the Account object

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" >
  <class name="Account, CustomerProfile" lazy="false">

    <id name="Identifier" column="Account_Id" access="field.camelcase">
      <generator class="identity"/>
    </id>

    <!-- How do I map to the AccountAttributes table here to get the correct set? -->
    <bag name="AccountAttributes" access="field.camelcase" table="AccountAttribute">
      <key column="Account_Id" />
      <one-to-many class="AccountAttribute, CustomerProfile"/>
    </bag>

  </class>
</hibernate-mapping>

Thanks,

Kyle


I believe your problem is due to the fact that you have given your subclass its own primary key in the table, i.e. AccountAttribute_id in AccountAttribute.

As you said that you are using table-per-subclass all of your subclass tables should use the superclass primary key, therefore the AccountAttribute table should only have Attribute_id as a primary key which is also a foreign key back to the Attribute table.

Once you've made these changes your mapping should then work because it is using the correct <key />


Refs:

  • http://docs.jboss.org/hibernate/core/3.5/reference/en/html/inheritance.html#inheritance-tablepersubclass
  • http://codebetter.com/iancooper/2009/01/21/introduction-to-nhibernate-pt-4/
  • http://ang3lfir3.wordpress.com/2009/08/06/table-per-subclass-inheritance-mapping-with-fluent-nhibernate/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜