hibernate—懒加载问题解决

错误:

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不会提前关闭。

转载于:https://my.oschina.net/wuzhentao/blog/1217792

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值