![](/img/trans.png)
[英]Hibernate inserts duplicates into one-to-many collection - eager fetch
[英]Hibernate one-to-many mapping eager fetch not working
学院与学生实体之间存在一对多的关系。
学院
@Entity
public class College {
private int collegeId;
private String collegeName;
private List<Student> students;
@Id
@GeneratedValue
public int getCollegeId() {
return collegeId;
}
public void setCollegeId(int collegeId) {
this.collegeId = collegeId;
}
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
@OneToMany(targetEntity=Student.class, mappedBy="college", cascade=CascadeType.ALL, fetch=FetchType.EAGER )
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
}
学生
@Entity
public class Student {
private int studentId;
private String studentName;
private College college;
@Id
@GeneratedValue
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
@ManyToOne
@JoinColumn(name="college_id")
public College getCollege() {
return college;
}
public void setCollege(College college) {
this.college = college;
}
}
我是休眠的新手,因此根据我的理解,如果我将fetchtype设置为FetchType.EAGER
那么每当我查询单个大学对象相关学生对象时,都会自动获取。我使用了以下查询,
College college = (College) session.get(College.class, id);
正确加载了college
对象,但是当我返回college.getStudents()
,我将得到null
。 我是否缺少某些东西,或者这是正确获取古怪的东西的正确方法?
您的代码看起来还不错,但是您可以尝试以下操作,让我们知道它是否有效。
您在College.java中的代码行:
@OneToMany(targetEntity=Student.class, mappedBy="college", cascade=CascadeType.ALL, fetch=FetchType.EAGER )
public List<Student> getStudents() {
return students;
}
请尝试将其替换为:
@OneToMany(targetEntity=Student.class, mappedBy="college", cascade=CascadeType.ALL, fetch=FetchType.EAGER )
@JoinColumn(name="college_id") // join column is in table for Student
public List<Student> getStudents() {
return students;
}
希望这对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.