懒加载错误

错误日志:

  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 getFixedAreas() {
        return fixedAreas;
        }
        只要加上了@JSON(serialize = false),返回的数据格式里不会含有fixedAreas字段及数据,
        可以理解为过滤掉了fixedAreas数据

    第二种解决方案:在web.xml中配置,延长EntityManager的生命周期,类似Hibernate里面延长Sesseion的生命周期
        
        OpenEntityManagerInView
        org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
        

        
        OpenEntityManagerInView
        / *
        

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

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

你可能感兴趣的:(异常,懒加载问题)