jap使用時遇到failed to lazily initialize a collection of XXXX 問題


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已經關閉,出現報錯。

解決方法:

  1. 將懶加載替換成急加載fetch=FetchType.EAGER。不過,這樣子違背了初始的想法,最好不要這樣;
  2. 修改配置文件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異常分析與解決

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM