簡體   English   中英

org.hibernate.LazyInitializationException:未能延遲初始化角色集合:studentsystem2.ikubinfo.entity.Student.classes

[英]org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: studentsystem2.ikubinfo.entity.Student.classes

我有這個錯誤,我找不到發生的原因。 不幸的是,我無法與其他問題聯系起來。

SEVERE: Servlet.service() for servlet [rest] in context with path [/studentsystem2] threw exception [Request processing failed; nested exception is org.modelmapper.MappingException: ModelMapper mapping errors:

1) Converter org.modelmapper.internal.converter.CollectionConverter@2f75990d failed to convert java.util.List to java.util.List.

1 error] with root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: studentsystem2.ikubinfo.entity.Student.classes, could not initialize proxy - no Session

這是我的學生 class

學生.java

@Entity
@Table(name="student")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name="student_id")
    private long id;

    @NotNull
    @Column(name = "firstname")
    private String firstName;

    @NotNull
    @Column(name = "lastname")
    private String lastName;

    @OneToMany(mappedBy = "student", fetch = FetchType.LAZY)
    private List<Classroom> classes;

    @NotNull
    @Temporal(value = TemporalType.DATE)
    private Date birthdate;

    private boolean flag;

    public Student() {

    }

}

我已經使用 ModelMapper 依賴項從實體轉換為 model。 您可以在下面找到 StudentConverter class

StudentConverter.java

@Component
public class StudentConverter {

    private ModelMapper modelMapper = new ModelMapper();

    public StudentConverter() {

    }

    public Student toEntity(StudentModel model) {
        return modelMapper.map(model, Student.class);
    }

    public StudentModel toModel(Student student) {
        return modelMapper.map(student, StudentModel.class);
    }

    public List<StudentModel> toModel(List<Student> entityList) {
        List<StudentModel> modelList = new ArrayList<StudentModel>();
        for (Student student : entityList) {
            modelList.add(toModel(student));
        }
        return modelList;
    }
}

因為 modelmapper 試圖在事務上下文之外訪問(內部使用反射進行復制)集合( private List<Classroom> classes;Student實體的數據成員。 您必須使用fetch = FetchType.EAGER或者您可以加入以獲取此集合以及Student實體。

已編輯

我有同樣的問題。 首先,我添加了以下代碼:

“fetch = FetchType.EAGER”

但問題並沒有解決。

然后,我添加了以下代碼,而不是上面的代碼:“@LazyCollection (LazyCollectionOption.FALSE)”

問題就解決了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM