【问题标题】:Hibernate one-to-many mapping eager fetch not working休眠一对多映射急切获取不起作用
【发布时间】:2015-07-22 20:14:05
【问题描述】:

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

大学

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

}

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

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

college 对象已正确加载,但当我说college.getStudents() 作为回报时,我会得到null。我是否遗漏了某些东西,或者这是急切获取的正确方法。

【问题讨论】:

  • 我要问它:您是否 100% 确定存在数据。请向我们出示您的服务代码。
  • 那是不可能的。 Hibernate 永远不会给你一个空集合。如果它没有被急切地加载,它会延迟加载,并返回一个非空列表(如果学院没有任何学生,则为空)。向我们展示重现问题的完整测试,打开 SQL 日志记录,并告诉我们真正发生了什么。发生这种情况的唯一方法是,如果您自己在同一会话中创建了学院并将集合保留为空。
  • 请检查配置的AccessType。 access 属性允许您控制 Hibernate 在运行时如何访问该属性。默认情况下,Hibernate 将调用属性 get/set 对。如果您指定 access="field",Hibernate 将绕过 get/set 对并使用反射直接访问该字段。您可以通过命名实现接口 org.hibernate.property.PropertyAccessor 的类来指定自己的属性访问策略。
  • 如果集合包含数据并被延迟加载,那么它会从休眠中抛出一个LazyInitializationException(如果没有打开会话)。因此,请确保确实有数据映射到该字段。
  • 确保您的代码没问题,请提供您的服务类代码,我认为您缺少 setCollege 即 student.setCollege(CollegeClassObject);

标签: java hibernate hibernate-mapping hibernate-criteria


【解决方案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;
}

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 2013-10-16
    • 2011-04-07
    • 1970-01-01
    • 2014-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    相关资源
    最近更新 更多