首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

SpringMVC 整合 MyBatis 延遲加載導致 JSON 序列化失敗 500 錯誤的解決方案

     編輯:程式設計疑難解答

問題現象

配置 lazyLoadingEnabled=true 後,Controller 返回實體對象,Jackson 序列化時觸發懶加載,因 Session 已關閉拋出 LazyInitializationException,導致 HTTP 500。

三種解決方案

1. 關閉全局延遲加載(最簡單)

<setting name="lazyLoadingEnabled" value="false"/> <!-- mybatis-config.xml -->

所有關聯查詢改為急加載(resultMap 中 association/collection 默認 fetchType="eager")。

2. 開啟 Open Session In View (OSIV)

<filter>
    <filter-name>openSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.mybatis.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>openSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

將 Session 生命周期延長至視圖渲染結束,序列化時仍可觸發懶加載。注意:可能導致長事務、連接泄漏,生產環境慎用。

3. 使用 DTO/VO 切斷關聯(推薦)

定義專門的傳輸對象,只包含前端需要的字段,Service 層手動組裝或使用 resultMap 映射到 DTO,避免實體關聯對象被序列化。

public class UserDTO {
    private Long id;
    private String name;
    private List roles; // 只包含角色名,無權限等敏感字段
}

參考資料

博客詳細對比:SpringMVC MyBatis 懶加載 JSON 500 解決

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved