Hibernate one-to-many mapping eager fetch not working

风流意气都作罢 提交于 2019-12-24 03:06:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!