Search code examples
javahibernatelazy-initialization

Hibernate failed to lazily initialize a collection of role could not initialize proxy - no Session


I've been trying to figure out how to get this to work with a Lazy fetch type, but I can't quite figure it out.

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


}

The error is being thrown on the line Hibernate.initialize(students); or on the next line if that isn't there, on the students set, with the error in the title. Any help (that's not just set fetch type to Eager) would be appreciated.


Solution

  • There are various options:

    1. Call a method on the mapped relation
    2. Fetch Join in JPQL
    3. Fetch Join in Criteria API
    4. Named Entity Graph
    5. Dynamic Entity Graph

    For details please read: https://thorben-janssen.com/5-ways-to-initialize-lazy-relations-and-when-to-use-them/