具有此模型架构:
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 的数据透视表,其中包含两种类型的学生男生 and 大学生。该表包含对该人本身及其正在学习的课程的引用。
现在我想在加载时区分大学生和中学生Course实体。我这样做:
<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。
我可以做什么来避免这种情况?是否有可能在数据透视表中建立一种区分?或者我是否必须为每种子类创建特定的数据透视表?