Hibernate一对多映射急切获取无法正常工作

时间:2015-05-12 05:44:41

标签: java hibernate hibernate-mapping hibernate-criteria

大学与学院之间存在一对多的关系。学生实体。

学院

@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;
}

}

我是hibernate的新手,所以基于我的理解,如果我将fetchtype设置为FetchType.EAGER,那么每当我查询单个大学对象时,相关的学生对象都会自动获取。我使用了以下查询,

College college = (College) session.get(College.class, id);

college对象已正确加载,但当我说college.getStudents()作为回报时,我将获得null。我错过了什么,或者这是正确的获取方式。

1 个答案:

答案 0 :(得分:-1)

您的代码看起来不错,但是您可以在下面尝试并让我们知道它是否有效。

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;
}

希望这会对你有所帮助。