3
有了這個模型模式的子類:Hibernate的許多一對多使用相同的數據透視表
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>
現在我要爲大家介紹的課程實體,實現課程與學生之間的關係。當然,這是一個多對多的關係。假設我使用名爲tstudent_course的數據透視表,其中包含SchoolBoy和CollegeStudent這兩種類型的學生。這個表格包含了對人員本身和他正在學習的課程的參考。
現在我想在大學生和學校學生之間加入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。
我該怎麼做才能避免這種情況?是否有可能在數據透視表中建立一種歧視?或者我必須爲每種子類創建一個特定的數據透視表?
我正面臨着一個錯誤,person_type列似乎並不可用:''where clause''中的未知列。它是在tperson表還是在數據透視表中查找它?我知道這也可以加載整個學生集合,但它只是加載我需要迭代的值,實際上爲什麼要加載所有學生,如果我只需要特定情況?我在實時系統中工作,我需要儘可能快地完成任務。 –
順便說一句,實施它與兩個數據透視表(tstudent_college_course和tstudent_school_course)似乎正常工作。儘管我認爲這不是從DB關係角度看的最佳機會。 –
問題解決了,'where'子句進入'多對多'標籤。 –