3

拥有此模型架构:

Person
    |__ Student
            |__ SchoolBoy
            |__ CollegeStudent

我正在使用 Hibernate 3.6,并且我使用tperson表对所有类使用鉴别器列。我的映射是这样完成的:

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

现在我要介绍Course实体,实现课程和学生之间的关系。当然,这是一个多对多的关系。假设我使用了一个名为 tstudent_course 的数据透视表,其中包含SchoolBoyCollegeStudent两种类型的学生。此表包含对个人本身和他正在学习的课程的引用。

现在,当我加载课程实体时,我想区分大学生和学校学生。我这样做:

<set name="CollegeStudents" table="tstudent_course"
            inverse="true">
    <key>
        <column name="id_course" not-null="true" />
    </key>
    <many-to-many entity-name="CollegeStudent">
        <column name="id_person" not-null="true" />
    </many-to-many>
</set>

<set name="SchoolStudents" table="tstudent_course"
            inverse="true">
    <key>
        <column name="id_course" not-null="true" />
    </key>
    <many-to-many entity-name="SchoolBoy">
        <column name="id_person" not-null="true" />
    </many-to-many>
</set>

但是,作为数据透视表,它包含对每种类型学生的引用,它会尝试加载我的集合中的每个学生,并且我收到下一个异常:

Object with id: 2 was not of the specified subclass: 
   CollegeStudent (loaded object was of wrong class class SchoolBoy)

似乎 Hibernate 正在加入,但没有评估我拥有的具体学生类型,并试图在我的大学生集合中注入一个 SchoolBoy。

我能做些什么来避免这种情况?是否有可能在数据透视表中建立一种区分?还是我必须为每种子类创建一个特定的数据透视表?

4

1 回答 1

2

在您的集合中,您可以添加一个过滤器:

<set name="CollegeStudents" table="tstudent_course"
            inverse="true">
    <key>
        <column name="id_course" not-null="true" />
    </key>
    <many-to-many entity-name="CollegeStudent" where="person_type='COLLEGE_STUDENT'">
        <column name="id_person" not-null="true" />
    </many-to-many>
</set>

恕我直言,如果没有那个过滤器(只是一组所有学生),映射会更好。

于 2013-07-09T08:34:43.383 回答