Many To Many could not initialize proxy – no Session的解決方法

myskies發表於2018-05-17

could not initialize proxy - no Session的錯誤,一般出現在我們獲取一些實體的oneToManymanyToMany屬性時。這是由於JPA在查詢完畢後,立即釋放了session(實現了連線資料庫並查詢資料的功能). 而當我們查詢完畢後,再想獲取實體中的一些資訊時,便發生了上述錯誤。

示例

比如:

// 班級
class Klass {
...
    @OneToMany
    private List<Student> studentList;
...
}

Klass klass = klassRepository.findOneById(1L); // 開啟session,查詢,關閉session
klass.getStudents(); // 此時session已關閉,發生錯誤。

解決方法

1) 設定不要查詢後就關閉session:該方法不推薦,特別是小白。具體方法不闡述。
2) 設定lazy屬性.該方法適用於大部分情景。

class Klass {
...
    @OneToMany
    @Lazy(false)
    private List<Student> studentList;
...

3) 設定fetch屬性: 該方法適用於第2種解決方法不生效時.

class Klass {
...
    @OneToMany(fetch = FetchType.EAGER)
    private List<Student> studentList;
...

相關文章