当前位置: 首页 > 知识库问答 >
问题:

Hibernate未能懒惰地初始化一个角色集合不能初始化代理-没有会话

许照
2023-03-14
@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类型设置为Eager)都将不胜感激。

共有1个答案

郎意
2023-03-14

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

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

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

 类似资料: