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,有加载策略的问题,都是基于性能的考虑

  • 相关阅读:
    Surface RT2装Win10出现 "INF不包含数字签名信息"【已解决】
    树上倍增LCA模版
    sql注入
    python 调用 telnet
    ss
    【总结氵】2021.02.27 省选模拟
    2021.03.13省选模拟 抽卡(card)
    树链剖分之重链剖分 模板
    多项式求逆 模板
    NTT快速数论变换 模板
  • 原文地址:https://www.cnblogs.com/daimzh/p/12854502.html
Copyright © 2011-2022 走看看