Hibernate无法延迟初始化角色集合.无法初始化代理-无会话



我一直在想如何让它与Lazy fetch类型一起工作,但我不太明白。

@Entity
@Table(name = "module")
public class Module extends ReservationOption{
@Column
private String name;
@Column
private int credits;
@Column
private int weeks;
@Column(name = "no_of_lectures")
private int noOfLectures;
@Column(name ="no_of_practicals")
private int noOfPracticals;
@Column(name = "lecture_length")
private int lectureLength;
@Column(name = "practical_length")
private int practicalLength;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "takes",
joinColumns = @JoinColumn(name = "moduleID"),
inverseJoinColumns = @JoinColumn(name = "studentID")
)
private Set<Student> students = new HashSet<>();
public void addTakes(Student student){
IDatabase db = Database.getInstance();
if(!db.checkInTable(Student.class, student.getId())) db.add(student);
Hibernate.initialize(students);
students.add(student);
student.getModules().add(this);
db.update(this);
}
@Entity
@Table(name = "student")
public class Student extends Person{
/**
* Constructor for Student class, allows for object creation
* @param id From Person
* @param firstName From Person
* @param lastName From Person
*/
public Student(String id, String firstName, String lastName) {
super(id, firstName, lastName);
}
/**
* Blank constructor to allow for database interfacing
*/
public Student(){
super();
}
@ManyToMany(mappedBy = "students", fetch = FetchType.LAZY)
private Set<Module> modules = new HashSet<>();
@Override
public Set<Module> getModules() {
return modules;
}
public void setModules(Set<Module> modules) {
this.modules = modules;
}

}

在Hibernate.initialize(students(行上抛出错误;或者在下一行,如果没有,在学生组,标题中有错误。任何帮助(不仅仅是将fetch类型设置为Eagle(都将不胜感激。

检查代码路径以确保显式或隐式(例如通过Annotation(创建了会话。

"无会话";错误通常意味着您正在尝试调用Hibernate行为(即初始化,或只是访问一个惰性变量(,但没有启动任何事务/会话资源供其在其中操作。

通常,当我过去遇到这种情况时,是因为它是普通的java代码,要么没有适当地设置Hibernate(因此,不存在可连接的会话(,要么我已经设置了Hibernate,但代码找到了一个路径,它从未命中@Transactional注释,因此没有设置会话。

有各种选项:

  1. 调用映射关系上的方法
  2. JPQL中的Fetch Join
  3. 获取加入条件API
  4. 命名实体图
  5. 动态实体图

有关详细信息,请阅读:https://thorben-janssen.com/5-ways-to-initialize-lazy-relations-and-when-to-use-them/

最新更新