zoukankan      html  css  js  c++  java
  • 懒加载问题的解决方案

        在做项目的时候,一不小心就碰到懒加载的问题,今天做个总结(springdata-jpa):
        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,有加载策略的问题,都是基于性能的考虑

  • 相关阅读:
    团队第三次作业 ——需求分析
    个人作业——IM SDK 评测
    AFLW如何获取你想要的21点人脸关键点数据
    本地ubuntu下pycharm 如何利用远程开发环境时显示图片
    pandas如何去掉时间列的小时只保留日期
    如何通过numpy获得二维或多维数组的最大、小值索引
    怎么理解np.random.seed()?
    python+opencv2相机位姿估计
    Image Style Transfer:多风格 TensorFlow 实现
    python matplotlib 播放图片变化过程
  • 原文地址:https://www.cnblogs.com/daimzh/p/12854502.html
Copyright © 2011-2022 走看看