【问题标题】:Joining to a subclass of a Table per Class hierarchy in NHibernate在 NHibernate 中加入每个类层次结构的表的子类
【发布时间】:2011-01-20 08:18:11
【问题描述】:

我在 NHibernate 中使用每个子类映射继承的表。我有一个父 Attribute 表和一个孩子 AccountAttribute 表。子AccountAttribute 表中有另一个指向CustomerProfile 表的外键。 CustomerProfile 表与AccountAttribute 表有零个或多个关系;这意味着我将在我的CustomerProfile 类中收集AccountAttributes

如何将CustomerProfile 表映射到我的NHibernate 映射中的AccountAttribute 表,以便CustomerProfile 类与正确的AccountAttributes 相结合?

表格

属性: Attribute_Id (PK)

帐户属性: AccountAttribute_Id (PK); Attribute_Id (FK); CustomerProfile_Id (FK)

客户资料: CustomerProfile_Id (PK)

Attribute/AccountAttribute 层次结构的映射。

<?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="ValueText" column="Value_Txt" access="nosetter.camelcase" />
    </joined-subclass>

  </class>
</hibernate-mapping>

帐户对象的映射

<?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>

谢谢,

凯尔

【问题讨论】:

    标签: nhibernate mapping joined-subclass


    【解决方案1】:

    我相信您的问题是由于您在表中为子类提供了自己的主键,即AccountAttribute 中的AccountAttribute_id

    正如您所说,您正在使用 table-per-subclass 所有子类表都应该使用超类主键,因此 AccountAttribute 表应该只有 Attribute_id 作为主键这也是返回Attribute 表的外键。

    完成这些更改后,您的映射应该可以正常工作,因为它使用了正确的&lt;key /&gt;


    参考:

    【讨论】:

    • 我同意应该只有一个主键 - 不幸的是,这里有几件事对我不利。 #1 AccountAttribute 表中有一个可更新的字段 - 因此需要主键。 #2 CustomerProfile 和 AccountAttribute 之间的关系是必需的,因为这是一种向 CustomerProfile 动态添加属性(即城市、州、邮编等)的方式,而无需更改数据库架构。我越想越觉得继承不是处理这种映射的正确方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多