天天看点

SpringDataJpa的no Session错误的解决方案

解决no Session错误

错误代码:

Could not write content: could not initialize proxy - no Session (through reference chain: cn.lzj.aisell.common.UIPage[“rows”]->java.util.UnmodifiableRandomAccessList[0]->cn.lzj.aisell.domain.Employee[“department”]->cn.lzj.aisell.domain.Department_$$_jvste79_0[“id”]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session (through reference chain:

问题原因:

因为在数据懒加载时,关闭EntityManager之后,依然在使用它操作数据库

SpringDataJpa的no Session错误的解决方案

解决方案:

在web.xml中添加OpenEntityManagerInViewFilter

<!--解决获取部门懒加载noSession,配置JPA:OpenEntityMangerInViewFilter/Hibernater:OpenSessionMangerInViewFilter-->
    <!--Spring集成JPA必须配置-->
    <filter>
        <filter-name>OpenEntityMangerInViewFilter</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>OpenEntityMangerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
           

注意在Spring集成JPA时,必须配置OpenSessionMangerInViewFilter这个过滤器,否则会出现no Session错误

继续阅读