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异常分析与解决