Hibernate + Spring (quartz) 整合懒(延迟)加载问题

开发项目的时候 在一个Job中执行了数据库操作, 用的是懒加载,但是如下错误

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ......., no session or session was closed

项目中使用 hibernate 注解的方式配置懒加载, 不是xml配置文件,

下面列出从网上搜集到的解决方案

1, 报如下错误

org.hibernate.LazyInitializationException: could not initialize proxy - no Session at

解决方法:

在web.xml中,配置springSevlet的位置,使用org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter,代码如下:

  <filter>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Spring OpenEntityManagerInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

 

2, 一般是在定时任务quartzJob中,或者Junit测试中使用懒加载出现的错误, 报如下错误

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ......., no session or session was closed

解决方法:

添加事务配置注解。junit代码如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "file:src/main/webapp/WEB-INF/applicationContext.xml",
        "file:src/main/webapp/WEB-INF/demo-servlet.xml"})
@Transactional
public class Job {
  ...  
}

3, 还有一种方法说是lazy=false, 我再 OneToMany | ManyToOne 注解中设置fetch=FetchType.EAGER 也不起作用, 不知道用配置文件的行不行

转载于:https://www.cnblogs.com/duwei/p/4639741.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值