简体   繁体   English

休眠一对多映射渴望获取不起作用

[英]Hibernate one-to-many mapping eager fetch not working

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, 我是休眠的新手,因此根据我的理解,如果我将fetchtype设置为FetchType.EAGER那么每当我查询单个大学对象相关学生对象时,都会自动获取。我使用了以下查询,

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 . 正确加载了college对象,但是当我返回college.getStudents() ,我将得到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 : 您在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. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM