天天看點

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錯誤

繼續閱讀