错误:
Caused by: org.hibernate.LazyInitializationException:
failed to lazily initialize a collection of role:
cn.bos.domain.base.Courier.fixedAreas, could not initialize proxy - no Session
这上面的大概意思为:不能加载集- 这里是列表文本合,cn.bos.domain.base包下的Courier.fixedAreas属性,不能初始化代理。
原因:我在Courier对象中关联了下面的集合属性
@ManyToMany(mappedBy = "couriers")
private Set<FixedArea> fixedAreas = new HashSet<FixedArea>();
在做json懒加载的时候,不会去加载这个集合。因为实体的集合属性默认会被延迟加载,实体所关联的实体默认也会被延迟加载。
遇到这种异常的时候先要分析:到底要不要去加载这个集合对象
因为我返回的json对象是不需要这个集合对象,因此可以用@Json注解来排除不需要加载的属性
- 只需要在相应的get方法的上面加上@JSON(serialize=false)就能解决本次遇到的问题。
@JSON(serialize=false)
public Set<FixedArea> getFixedAreas() {
return fixedAreas;
}
这里有篇详细的文章讲解了 Hibernate 延迟加载剖析与代理模式应用
- 如果需要集合属性,解决方法如下 在web.xml文件中配置:
<filter>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
<!-- 指定org.springframework.orm.jpa.LocalEntityManagerFactoryBean在spring配置文件中的名称,默认值为entityManagerFactory
如果LocalEntityManagerFactoryBean在spring中的名称不是entityManagerFactory,该参数一定要指定,否则会出现找不到entityManagerFactory的例外 -->
<param-name>entityManagerFactoryBeanName</param-name>
<param-value>entityManagerFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
说明:上面的配置表示session不会提前关闭。