Could not write JSON: failed to lazily initialize a collection of role: com.blog.Entity.UserInfo.userRoles, could not initialize proxy - no Session;
nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.blog.yongyu.signInStart.Entity.UserInfo.userRoles, could not initialize proxy - no Session (through reference chain: com.blog..Entity.BaseClass.DataResult[\"data\"]->java.util.ArrayList[0]->com.blog.Entity.UserInfo[\"role\"])",
postman發送請求時,報錯信息如上。
原因在於:類User Info和Role使用OneToMany時,類UserInfo中用了懶加載fetch=FetchType.LAZY,導致在類UserInfo中取List<Role>時,加載數據的session已經關閉,出現報錯。
解決方法:
- 將懶加載替換成急加載fetch=FetchType.EAGER。不過,這樣子違背了初始的想法,最好不要這樣;
- 修改配置文件application.properties,設置 spring.jpa.open-in-view=true。解釋:Spring Boot中的spring.jpa.open-in-view = true屬性是什么?
別人的答案:JPA中的failed to lazily initialize a collection of role:xxxx no session or session was closed異常分析與解決