如何使用Hibernate将父级映射到子级?

时间:2015-04-08 19:53:26

标签: java hibernate hibernate-mapping

我有以下课程

class Condition{
    public Long id;
    public Long ParentConditionId;
    public Int order;
}

class NotCondition extends Condition {
    public Condition childCondition;
}

class BooleanCondition extends Condition {
    public Collection<Condition> children;
}

class StringCondition extends Condition {
    public String value;
}

这些类由条件表表示,其中包含以下列

Id bigint
Type varchar
ConditionOrder int
StringValue varchar
ParentConditionId bigint

如何使用hibernate映射将NotCondition映射到其子节点,以便子节点ParentConditionId列包含NotCondition的id?

我的映射文件是

<hibernate-mapping>
    <class name="conditions.Condition" table="Condition">
        <id column="Id" name="id" access="field">
            <generator class="increment"/>
        </id>

        <discriminator type="string" column="Type"/>
        <property name="order" column="ConditionOrder" access="field"/>
        <property name="parentConditionId" column="ParentConditionId" access="field"/>
        <subclass name="conditions.NotCondition" discriminator-value="NOT">
            <!-- What to put here? -->
        </subclass>
        <subclass name="conditions.BooleanCondition" discriminator-value="BOOLEAN">
            <list name="children" access="field" cascade="all" lazy="false">
                <key><column name="ParentConditionId"></column></key>
                <list-index column="ConditionOrder"/>
                <one-to-many class="conditions.Condition"/>
            </list>
        </subclass>
        <subclass name="conditions.StringCondition" discriminator-value="STRING" >
            <property name="value" column="StringValue" access="field"/>
        </subclass>
    </class>

</hibernate-mapping>

2 个答案:

答案 0 :(得分:0)

探索这些:

@Inheritance(strategy=InheritanceType.JOINED)

我建议你使用注释..

以下链接包含Annatation和xml配置..

link here

答案 1 :(得分:0)

首先,在Class Condition中,我将替换:

public Long ParentConditionId;

使用:

public Condition parentCondition;

我想映射是这样的:

<many-to-one name="parentCondition" class="conditions.Condition" column="ParentConditionId" />

然后,我将childCondition(在子类NotCondition中)映射为:

<one-to-one name="childCondition" class="conditions.Condition" property-ref="parentCondition" />