懒加载错误的三种处理方案

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sunguodong_/article/details/79083547
懒加载错误
Exception occurred during processing request: org.hibernate.LazyInitializationException: 
failed to lazily initialize a collection of role: cn.itcast.bos.domain.base.Courier.fixedAreas,
could not initialize proxy - no Session
org.apache.struts2.json.JSONException: org.hibernate.LazyInitializationException: 
failed to lazily initialize a collection of role: cn.itcast.bos.domain.base.Courier.fixedAreas, 
could not initialize proxy - no Session

第一种解决方案:在getFixedAreas方法上加上@JSON(serialize = false)
@JSON(serialize = false)
public Set<FixedArea> getFixedAreas() {
return fixedAreas;
}
只要加上了@JSON(serialize = false),返回的数据格式里不会含有fixedAreas字段及数据,
可以理解为过滤掉了fixedAreas数据

第二种解决方案:在web.xml中配置,延长EntityManager的生命周期,类似Hibernate里面延长Sesseion的生命周期
<filter>
<filter-name>OpenEntityManagerInView</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenEntityManagerInView</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

第三种解决方案:不配置OpenEntityManagerInViewFilter,不配置@JSON(serialize = false),设置为立即加载
@ManyToMany(mappedBy = "couriers",fetch=FetchType.EAGER)
private Set<FixedArea> fixedAreas = new HashSet<>();
此时,返回的数据格式里有fixedAreas字段及数据
获取A对象时,A对象关联B对象,FetchType默认是立即加载
获取A对象时,A对象关联B对象的集合,FetchType默认是懒加载

总结:不管是Hibernate还是JPA,有加载策略的问题,都是基于性能的考虑

猜你喜欢

转载自blog.csdn.net/sunguodong_/article/details/79083547
今日推荐