学院和学生实体之间存在一对多的关系。
大学
@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
。我是否遗漏了一些东西,或者这是快速获取的正确方法吗?
我不知道为什么,但在将两个 FetchType 设置为 EAGER 后我可以获取。
学生班
@ManyToOne(fetch=FetchType.EAGER)
private College college;
拼贴.班
@OneToMany(mappedBy="collage",fetch=FetchType.EAGER)
private List<Student> students;
您的代码看起来不错,但是您可以尝试一下并让我们知道它是否有效。
您在 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;
}
希望这对您有帮助。