配置 lazyLoadingEnabled=true 後,Controller 返回實體對象,Jackson 序列化時觸發懶加載,因 Session 已關閉拋出 LazyInitializationException,導致 HTTP 500。
<setting name="lazyLoadingEnabled" value="false"/> <!-- mybatis-config.xml -->
所有關聯查詢改為急加載(resultMap 中 association/collection 默認 fetchType="eager")。
<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 生命周期延長至視圖渲染結束,序列化時仍可觸發懶加載。注意:可能導致長事務、連接泄漏,生產環境慎用。
定義專門的傳輸對象,只包含前端需要的字段,Service 層手動組裝或使用 resultMap 映射到 DTO,避免實體關聯對象被序列化。
public class UserDTO {
private Long id;
private String name;
private List roles; // 只包含角色名,無權限等敏感字段
}
博客詳細對比:SpringMVC MyBatis 懶加載 JSON 500 解決