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); 行上抛出错误;或者在下一行,如果不存在,在学生集上,标题中有错误。任何帮助(不仅仅是将提取类型设置为 Eager)将不胜感激。

解决方法

有多种选择:

  1. 调用映射关系的方法
  2. 在 JPQL 中获取连接
  3. 在 Criteria API 中获取连接
  4. 命名实体图
  5. 动态实体图

详情请阅读: https://thorben-janssen.com/5-ways-to-initialize-lazy-relations-and-when-to-use-them/

,

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

“无会话”错误通常意味着您正在尝试调用 Hibernate 行为(即初始化,或仅访问惰性变量),但没有启动事务/会话资源供其在其中运行。

过去发生这种情况时,通常是因为它是普通的 Java 代码,要么没有适当地设置 Hibernate(因此,不存在可供连接的 Session),要么我已经设置了 Hibernate,但是代码以这样的方式找到了一条路径,它永远不会碰到@Transactional 注释,因此没有设置会话。