HTTP Status 500 - Could not write content: failed to lazily initialize a collection of role

本文介绍在SpringMVC中处理多对多关系时遇到的延迟加载异常问题及其解决方案。通过配置OpenEntityManagerInViewFilter过滤器,确保视图层能够正确获取到关联数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在spring mvc中创建多对多映射类时,对应两张表分别为app和app_list,

类App, 需要添加集合:

private Set<App> mapApps = new HashSet<App>();

类AppList,需要添加集合:

@ManyToMany(mappedBy="mapApps")  
private Set<AppList> app_lists = new HashSet<AppList>();

在查询的时候,返回结果到页面时,出现标题所示错误。
原因是:
关联关系中采用fetch=FetchType.LAZY,返回给view层(jsp代码)的时候,由于加载领域对象的JPA Session已经关闭,导致这些延迟加载的数据访问异常。

解决办法是,在web.xml中添加OpenEntityManagerInViewFilter过滤器。

JPA:

<filter>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class></filter>

<filter-mapping>
    <filter-name>OpenSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Hibernate:

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

参考:
Spring的OpenEntityManagerInViewFilter http://whoosh.iteye.com/blog/1300721

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值