问题
There is a one to many relationship between College & student entities.
College
@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;
}
}
Student
@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;
}
}
I am a newbie to hibernate, so based on my understanding if i set the fetchtype as FetchType.EAGER
then whenever i query for a single college object related student objects are fetched automatically.I have used following query,
College college = (College) session.get(College.class, id);
college
object is loaded properly but when i say college.getStudents()
in return i'll get null
. Am i missing something or is this the proper way to fetch eagarly.
回答1:
Your code looks ok, but can you please try below and let us know is it works or not.
Your line of code in College.java :
@OneToMany(targetEntity=Student.class, mappedBy="college", cascade=CascadeType.ALL, fetch=FetchType.EAGER )
public List<Student> getStudents() {
return students;
}
Please try to replace this with :
@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;
}
Hope this helps you.
来源:https://stackoverflow.com/questions/30182674/hibernate-one-to-many-mapping-eager-fetch-not-working