JPA中的failed to lazily initialize a collection of role:xxxx no session or session was closed异常分析与解决

解决JPA LazyInitializationException
本文探讨了在基于JPA的单元测试中遇到的LazyInitializationException异常,详细分析了问题产生的原因,并通过调整实体关系映射及配置解决了该问题。

引言: JPA是一种非常流行和常用的持久化框架标准,其下可以对接若干种不同的实现,在不同的父子表管理中,经常会碰到no Session的问题,该如何解决呢?

1. 问题的引出

  在进行基于JPA的单元测试中,我们使用JUnit来进行测试数据库的关联表信息读取,结果得到如下错误信息:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.rain.wx.meal.model.DishCategory.dishes, could not initialize proxy - no Session  
  2.     at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:587)  
  3.     at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:204)  
  4.     at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:566)  
  5.     at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:135)  
  6.     at org.hibernate.collection.internal.PersistentBag.get(PersistentBag.java:449)  
  7.     at com.rain.wx.meal.service.DishServiceTest.testDishes(DishServiceTest.java:86)  
  8.     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
  9.     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)  
  10.     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)  
  11.     at java.lang.reflect.Method.invoke(Method.java:497)  
  12.     at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)  
  13.     at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)  
  14.     at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)  
  15.     at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)  
  16.     at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)  
  17.     at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)  
  18.     at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)  
  19.     at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)  
  20.     at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)  
  21.     at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)  
  22.     at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  
  23.     at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)  
  24.     at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)  
  25.     at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)  
  26.     at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)  
  27.     at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)  
  28.     at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)  
  29.     at org.junit.runners.ParentRunner.run(ParentRunner.java:363)  
  30.     at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)  
  31.     at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)  
  32.     at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)  
  33.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)  
  34.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)  
  35.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)  
  36.     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)  
    经过分析,其中的关键词是: could not initialize proxy - no Session; 基于JPA的实现来分析,就是在进行数据库访问之时,当前针对数据库的访问与操作session已经关闭且释放了,故提示no Session可用。

2.  代码实现分析

    让我们来看看具体的代码吧

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Entity  
  2. @Table(name="dish_category")  
  3. @Data  
  4. @EqualsAndHashCode(callSuper=false)  
  5. @JsonRootName(value="category")   
  6. public class DishCategory extends BaseEntity {  
  7.     private static final long serialVersionUID = -7189824224534351030L;  
  8.   
  9.     @Column  
  10.     private String name;  
  11.       
  12.     @Column  
  13.     private String description;  
  14.       
  15.       
  16.     @OneToMany  
  17.     @JoinColumn(name="category_id",referencedColumnName="id")  
  18.     private List<MealDish> dishes;  
  19. }  
  另外一个实体Bean为MealDish, 其代码为:
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Entity  
  2. @Table(name = "dish")  
  3. @JsonRootName(value="dish")   
  4. //@Lazy(value=false)  
  5. public class MealDish extends BaseEntity {  
  6.     private static final long serialVersionUID = -3982356728880195795L;  
  7.   
  8.     @Column  
  9.     private String name;  
  10.   
  11.     @Column  
  12.     private float price;  
  13.   
  14.     @Column(name = "img_url")  
  15.     private String imgUrl;  
  16.   
  17.     @Column(name="category_id")  
  18.     private long categoryId;  
  19.   
  20.     @Column  
  21.     private boolean active;  
  22.   
  23.     // 销售数量  
  24.     @Column  
  25.     private int soldCount;  
  26.         .......  
  27. }  
其中Repository/Service的代码分别如下: 
[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Service  
  2. public class DishServiceImpl implements DishService {   
  3.        @Transactional  
  4.     @Override  
  5.     public List<DishCategory> getDishCategory() {  
  6.         return this.dishCategoryRepo.findAll();  
  7.     }  
  8.    ........  
  9.  }  
Repository相关的代码都是空代码,无实际的实现,这里再次忽略。

单元测试的代码内容:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Test  
  2.    public void testDishes() throws JsonProcessingException {  
  3.     ObjectMapper mapper = new ObjectMapper();  
  4.       
  5.     List<DishCategory> categories = this.dishService.getDishCategory();  
  6.       
  7.     for (DishCategory category  : categories) {  
  8.         // log.debug(String.valueOf(category.getDishes().get(0)));    
  9.     }  
  10.       
  11.     String jsonStr = mapper.writeValueAsString(categories);  
  12.       
  13.     log.info(jsonStr);  
  14.    }  
3. 问题分析

  基于对Hibernate和JPA的理解,在ORM中,其为了提升性能使用了Lazy加载,就是在使用的时候,才会加载额外的数据,故导致了在使用之时再加载数据之时, session失效的问题出现。所以问题的目标点实现提前加载数据。

4. 问题的解决

    尝试1:  在Service方法中新增了@Transactional进行事务添加

    结果1:  无效

   尝试2: 在@OneToMany的方法上,使用@Lazy(false)

    结果2:  无效

    尝试3: 在@OneToMany的参数中使用fetch=FetchType=Eager

    结果3:   问题解决

    尝试4: 在application.properties的配置文件中新增spring.jpa.open-in-view=true

    结果4: 问题解决

   方法3的正确的代码内容:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Entity  
  2. @Table(name="dish_category")  
  3. @Data  
  4. @EqualsAndHashCode(callSuper=false)  
  5. @JsonRootName(value="category")   
  6. public class DishCategory extends BaseEntity {  
  7.     private static final long serialVersionUID = -7189824224534351030L;  
  8.   
  9.     @Column  
  10.     private String name;  
  11.       
  12.     @Column  
  13.     private String description;  
  14.       
  15.       
  16.     @OneToMany(fetch=FetchType.EAGER)  
  17.     @JoinColumn(name="category_id",referencedColumnName="id")  
  18.     private List<MealDish> dishes;  
  19. }  

方法4的解释与说明:

   这个设置选项:

spring.jpa.open-in-view=true
  其实是之前的 openEntityManagerInViewInterceptor ,解决在Spring MVC与JPA之间Session的声明周期问题

5. 总结

    核心问题在于解决延迟加载为及时加载,及时加载会消耗一定的资源,将其程序的性能,请注意这个问题。



原博 http://blog.youkuaiyun.com/blueheart20/article/details/52912023

<think>好的,我需要解决用户提出的Hibernate懒加载初始化集合时出现的“no Session异常问题。用户遇到了org.hibernate.LazyInitializationException,这通常是因为在Session关闭后尝试访问延迟加载的集合导致的。我应该根据提供的引用资料,整理出可行的解决方案,并按照用户的要求用中文回答,结构清晰,分步骤说明。 首先,看看用户提供的引用内容。引用3提到,当lazy设置为true时,在Session关闭后无法加载关联对象,解决方法包括在Session未关闭前调用Hibernate.initialize()或者访问集合的size()方法。引用4建议在映射文件中设置lazy="false"来关闭延迟加载。引用2提到了其他可能的解决方法,但用户给出的引用中并未详细说明,可能需要结合常见做法补充。 接下来,我需要将这些方法归纳成几个步骤,并详细说明每种方法的适用场景和注意事项。例如,方法一可以是在Session关闭前初始化代理对象,这需要在数据访问层处理。方法二则是调整延迟加载配置,可能影响性能。方法三可能涉及事务管理,确保操作在Session开启状态下进行。另外,可能还需要提到Open Session in View模式,虽然用户提供的引用中没有直接提到,但这是常见的解决方案之一,不过需要谨慎使用,避免事务过长的问题。 还要注意用户提到的代码示例,比如Hibernate.initialize(pojo.getChildren())或调用size()方法。需要解释这些代码的作用和使用方式。同时,设置lazy="false"虽然简单,但可能导致不必要的数据库查询,影响性能,需要权衡利弊。 另外,用户可能需要了解为什么会出现这个异常,所以需要简要解释原因:Hibernate的延迟加载机制在Session关闭后无法继续加载数据,导致异常。这样用户能更好地理解解决方案的逻辑。 最后,确保回答结构清晰,分点说明,每个方法都有步骤和注意事项,可能的问题。同时,生成的相关问题需要主题相关,帮助用户进一步了解其他可能的问题或优化方法。</think>### Hibernate懒加载异常“could not initialize proxy - no Session解决方案 当使用Hibernate的延迟加载(Lazy Loading)机制时,如果在Session关闭后尝试访问未初始化的关联对象或集合,会抛出`org.hibernate.LazyInitializationException`。以下是具体解决步骤: --- #### **方法一:在Session关闭前手动初始化代理对象** **步骤:** 1. 在数据访问层(DAO层)的查询方法中,通过`Hibernate.initialize()`显式初始化关联对象或集合。 ```java public Pojo getPojoWithChildren(Long id) { Session session = sessionFactory.getCurrentSession(); Pojo pojo = session.get(Pojo.class, id); Hibernate.initialize(pojo.getChildren()); // 强制初始化集合 return pojo; } ``` 2. 或者在业务逻辑中访问集合的某个方法(如`.size()`),触发初始化: ```java pojo.getChildren().size(); // 调用此方法会触发数据加载 ``` **注意事项** 此操作必须在Session未关闭前执行,通常在事务范围内完成[^3]。 --- #### **方法二:调整延迟加载配置** **步骤:** 1. 在实体映射文件(`.hbm.xml`)中,将关联字段的`lazy`属性设为`false`: ```xml <set name="children" lazy="false"> <!-- 关闭延迟加载 --> <key column="parent_id"/> <one-to-many class="Child"/> </set> ``` - 或使用JPA注解(如`@OneToMany(fetch = FetchType.EAGER)`)。 **注意事项** 关闭延迟加载会导致关联数据立即加载,可能增加数据库查询次数,需权衡性能影响[^4]。 --- #### **方法三:延长Session生命周期(事务边界扩展)** **步骤:** 1. 使用Spring的`@Transactional`注解扩展事务范围,确保在业务操作中Session始终开启: ```java @Transactional // 事务覆盖整个方法,Session在此期间保持开启 public void processPojo(Long id) { Pojo pojo = pojoRepository.findById(id); pojo.getChildren().forEach(child -> {...}); // 安全访问集合 } ``` **注意事项** 需确保事务管理配置正确,避免事务过长导致数据库连接池耗尽。 --- #### **方法四:使用Open Session in View模式(谨慎使用)** **步骤:** 1. 在Web应用中,通过过滤器(如Spring的`OpenSessionInViewFilter`)保持Session开启直到视图渲染完成。 ```xml <!-- web.xml配置 --> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> ``` **注意事项** 此模式可能掩盖性能问题,且需确保事务Session边界合理匹配,避免内存泄漏[^3]。 --- ### **根本原因分析** Hibernate的延迟加载依赖`Session`上下文。当Session关闭后,代理对象无法连接数据库加载数据,从而抛出异常解决方法的核心是**确保数据加载在Session有效期内完成**。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值