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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.