nhibernate <subclass> <join>嵌套另一个子类映射(导致叶类重复插入)</join> </subclass>

时间:2010-07-02 12:43:16

标签: nhibernate nhibernate-mapping

这种映射有什么问题? 在保存Class3的实例时,将插入Table_2中的两行!

第一行将Column4设置为null并更正Column3的值, 第二行将Column3设置为null并更正Column4的值!

  <class name="Class1" table="Table_1">
    <id name="Column1">
      <generator class="native" />
    </id>
    <discriminator column="ColumnDisc" />
    <property name="Column2" type="int" />
    <subclass name="Class2">
       <join table="Table_2">
         <key column="Column1" />
         <property name="Column3" type="int" />
       </join>
       <subclass name="Class3" >
          <join table="Table_2">
            <key column="Column1" />
            <property name="Column4" type="int" />
          </join>
       </subclass>
    </subclass>
  </class>

1 个答案:

答案 0 :(得分:1)

您在哪里为每个派生类型设置鉴别器值?

如果我相信您在评论中指向的链接,则类映射如下所示:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.javalobby.tnt.hib.User" table="USER" lazy="false">
        <id name="id" type="long" column="ID">
        <generator class="identity" />
    </id>

    <discriminator column="type" type="string"/>

    <property name="firstName" column="first_name"/>
    <property name="lastName" column="last_name"/>

    <subclass name="com.javalobby.tnt.hib.Employee" discriminator-value="employee">
        <join table="employee">
            <key column="id"/>
            <property name="jobTitle" column="job_title"/>
            <many-to-one name="supervisor" column="supervisor_id" not-null="true" />
        </join>
        <subclass name="com.javalobby.tnt.hib.Employer" discriminator-value="employer">
            <set name="subordinates">
                <key column="supervisor_id" not-null="true"/>
                <one-to-many class="com.javalobby.tnt.hib.Employee"/>
            </set>
            <join table="employer">
                <key column="id"/>
                <property name="companyCarBrand" column="company_car_brand"/>
            </join>
        </subclass>
    </subclass>
</class>

如果我将您的映射与此映射进行比较,则您的discriminator-value代码中缺少<subclass>属性。

<class name="Class1" table="Table_1">
    <id name="Column1">
        <generator class="native" />
    </id>
    <discriminator column="ColumnDisc" />

    <property name="Column2" type="int" />

    <subclass name="Class2"> <!-- The discriminator-value="" is missing here... -->
      <join table="Table_2">
        <key column="Column1" />
        <property name="Column3" type="int" />
      </join>
      <subclass name="Class3" > <!-- The discriminator-value="" is missing here... -->
        <join table="Table_2">
          <key column="Column1" />
          <property name="Column4" type="int" />
        </join>
      </subclass>
    </subclass>
  </class>

确保为要映射的每个子类设置正确的鉴别器值。我建议尝试一下,弄清楚它是否更好,或者是否会引发另一个问题。 =)

希望这有帮助! =)