Hibernate如何在join-subclass中进行区分

时间:2013-07-04 09:12:06

标签: hibernate

假设我有以下Entity模型并使用Hibernate 3.6:

Person
    |__ Student
            |__ SchoolBoy
            |__ CollegeStudent

我在数据库中的表格是 tperson tstudent 。因为我正在使用hibernate映射文件,所以我在下面将其声明为Person实体定义:

<joined-subclass name="Student" table="tstudent">
    <key column="id_person" />
</joined-subclass>

作为SchoolBoy,类似于CollegeStudent,我想为两个(tstudent)使用相同的表,具有学生类型鉴别器列,而我保留两个类。我的问题是,一旦你进入一个连接子类,Hibernate似乎不允许使用discriminator列。

是否有解决方法?

更新

这就是我现在所拥有的:

<class name="Person">
    <id name="Id" column="id" type="integer">
        <generator class="increment" />
    </id>
    <joined-subclass name="Student" table="tstudent">
        <key column="id_person" />
        <joined-subclass name="SchoolBoy" table="tschoolboy">
            <key column="id_person" />
        </joined-subclass>
        <joined-subclass name="CollegeStudent" table="tcollegestudent">
            <key column="id_person" />
        </joined-subclass>
    </joined-subclass>
</class>

这就是我希望在映射的连接部分中拥有的内容:

<joined-subclass name="Student" table="tstudent">
    <key column="id_person" />
    <discriminator column="student_type" />
    <subclass name="SchoolBoy" discriminator-value="SCHOOL_BOY" />
    <subclass name="CollegeStudent" discriminator-value="COLLEGE_STUDENT" />
</joined-subclass>

1 个答案:

答案 0 :(得分:6)

Hibernate文档说:

  

Hibernate不支持在同一根<subclass>元素下混合<joined-subclass><union-subclass><class>映射。通过组合<class><subclass>元素,可以将每个层次结构的表和每个子类策略的表混合在同一个<join>元素中

在您的情况下,您需要将discriminator列移动到tperson表,并使用join元素为学生类添加额外的属性。

<class name="Person" table="tperson" discriminator-value="PERSON">
    <id name="Id" column="id" type="integer">
        <generator class="increment" />
    </id>
    <discriminator column="person_type" />
    <subclass name="Student" discriminator-value="STUDENT">
        <key column="id_person" />
        <subclass name="SchoolBoy" discriminator-value="SCHOOL_BOY">
            <join table="tstudent">
                <key column="id_person" />
                ...
            </join>
        </subclass>
        <subclass name="CollegeStudent" discriminator-value="COLLEGE_STUDENT">
            <join table="tstudent">
                <key column="id_person" />
                ...
            </join>
        </subclass>
    </subclass>
</class>

您还可以在Student子类元素中为所有学生共有的属性添加联接