【问题标题】:Hibernate failed to lazily initialize a collection of role could not initialize proxy - no SessionHibernate 无法懒惰地初始化角色集合 无法初始化代理 - 没有会话
【发布时间】:2021-06-15 02:55:01
【问题描述】:

我一直在试图弄清楚如何让它与 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 type 设置为 Eager)将不胜感激。

【问题讨论】:

    标签: java hibernate lazy-initialization


    【解决方案1】:

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

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

    通常当这种情况发生在我身上时,这是因为它是纯 java 代码,要么没有正确设置 Hibernate(因此,不存在 Session 可以固定),要么我已经设置了 Hibernate,但是代码找到了一条永远不会碰到@Transactional 注释的路径,因此没有设置任何会话。

    【讨论】:

      【解决方案2】:

      有多种选择:

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

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

      【讨论】:

        猜你喜欢
        • 2016-11-10
        • 2014-05-03
        • 2021-08-20
        • 2020-11-25
        • 2021-11-27
        • 1970-01-01
        • 2017-01-30
        • 2016-06-04
        • 2018-11-21
        相关资源
        最近更新 更多