2015-05-08 66 views
0

將兩個OneToMany關聯添加到我的實體類似乎不起作用。如果我刪除其中一個,它工作正常。JPA實體是否可以有多個OneToMany關聯?

@Entity 
@Table(name = "school") 
public class School { 

    private List<Teacher> teachers; 
    private List<Student> students; 

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "school", fetch = FetchType.EAGER) 
    public List<Teacher> getTeachers() 
     return this.teachers; 
    } 
    public void setTeachers(List<Teacher> teachers) { 
     this.teachers = teachers; 
    } 

    @OneToMany(cascade=CascadeType.ALL, mappedBy = "school", fetch = FetchType.EAGER) 
    public List<Student> getStudents() 
     return this.students; 
    } 
    public void setStudents(List<Student> teachers) { 
     this.students = students; 
    } 
} 

然後在TeacherStudent我有正確的ManyToOne註釋

@Entity 
@Table(name = "teacher") 
public class Teacher { 
    private School school; 

    @ManyToOne 
    @JoinColumn(name = "school_id") 
    public School getSchool() { 
     return this.school; 
    } 
    public void setSchool(School school) { 
     this.school = school; 
    } 
} 

@Entity 
@Table(name = "student") 
public class Student { 
    private School school; 

    @ManyToOne 
    @JoinColumn(name = "school_id") 
    public School getSchool() { 
     return this.school; 
    } 
    public void setSchool(School school) { 
     this.school = school; 
    } 
} 

我也有id領域與正確的註釋(@Id@GeneratedValue

所以對我來說好像我在同一班級中不能有多於一個@OneToMany。它是否正確?

+1

不,它根本不正確。你可以擁有儘可能多的你想要的。你是什​​麼意思「它不工作」? – Kayaman

+0

可能是兩個關係具有相同名稱的問題? –

+0

當我檢索用戶時,沒有任何數據從數據庫返回。沒有堆棧跟蹤,甚至沒有警告。我可以看到hibernate映射了所有類 – steven35

回答

2

只要only one is EAGER可以有多個一對多關聯。

雖然您可以使用Set instead of List繞過此異常,但這不是一件好事,因爲您最終會得到一個笛卡爾積。

Best thing to do is to not use EAGER at all。您應該對所有關聯使用LAZY,並且熱切希望獲取與query-time FETCH directive關聯的many-to-oneone-to-one關聯以及最多一個one-to-many關聯。

如果您想要獲取多個one-to-many關聯,則應該使用方法進行第2或第3關聯,因爲3個簡單的select語句優於笛卡爾乘積。

+0

我今天晚些時候會嘗試一下,如果它有效,請接受你的答案。在此先感謝,我一直有一段時間的問題 – steven35

+0

更改爲設置解決了問題。謝謝 – steven35

相關問題