Hibernate:2个子类映射相同的键列

时间:2015-03-10 10:21:37

标签: java hibernate orm one-to-many hibernate-mapping

我想在子类中映射相同的键列,本例中为parent_id。 ClientProfileDO和BusinessProfileDO都继承自UserProfileDO。它们位于同一个表USERPROFILE上。因此,它们在Contact表中引用相同的外键。这在逻辑上是不正确的吗?

<hibernate-mapping    package="com.rentorama2.frontpage.client.serialize"default-lazy="false">
<class name="UserProfileDO" table="USERPROFILE">
<id name="oid" type="long" column="oid" >
    <generator class="increment">
        <param name="initial_value">1</param>
    </generator>
</id>
<discriminator column="dcolumn" type="string" length="5"/>
<property name="acctOid">
    <column name="acctOid" />
</property>  
<property name="email">
    <column name="email"/>
</property>

<subclass name="ClientProfileDO" discriminator-value="CP">
    <list name="c_contacts" cascade="all">
        <key column="parent_id" not-null="true"/>
        <index column="idx"/>
        <one-to-many class="Contact"/>
    </list>
</subclass> 
<subclass name="BusinessProfileDO" discriminator-value="BP">
    <property name="b_updateAnnouncement">
        <column name="updateAnnouncement"/>
    </property>
    <list name="b_contacts" cascade="all">
        <key column="parent_id" not-null="true"/>
        <index column="idx"/>
        <one-to-many class="Contact"/>
    </list>
</subclass>
</class>

1 个答案:

答案 0 :(得分:0)

我认为您应该将Contact一对多关联移动到UserProfileDO基类:

<hibernate-mapping    package="com.rentorama2.frontpage.client.serialize"default-lazy="false">
    <class name="UserProfileDO" table="USERPROFILE">
    <id name="oid" type="long" column="oid" >
        <generator class="increment">
            <param name="initial_value">1</param>
        </generator>
    </id>
    <discriminator column="dcolumn" type="string" length="5"/>
    <property name="acctOid">
        <column name="acctOid" />
    </property>  
    <property name="email">
        <column name="email"/>
    </property>

    <list name="contacts" cascade="all">
        <key column="parent_id" not-null="true"/>
        <index column="idx"/>
        <one-to-many class="Contact"/>
    </list>

    <subclass name="ClientProfileDO" discriminator-value="CP">

    </subclass> 
    <subclass name="BusinessProfileDO" discriminator-value="BP">
        <property name="b_updateAnnouncement">
            <column name="updateAnnouncement"/>
        </property>
    </subclass>
</class>

UserProfileDO类将有一个Contact列表:

private List<Contact> contacts = new ArrayList<>();

public List<Contact> getContacts() {
    return contacts;
}

public void getContacts(List<Contact> contacts) {
    this.contacts = contacts;
}