引言: JPA是一种非常流行和常用的持久化框架标准,其下可以对接若干种不同的实现,在不同的父子表管理中,经常会碰到no Session的问题,该如何解决呢?
1. 问题的引出
在进行基于JPA的单元测试中,我们使用JUnit来进行测试数据库的关联表信息读取,结果得到如下错误信息:
[html] view plain copy
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
1. @Entity
2. @Table(name="dish_category")
3. @Data
4. @EqualsAndHashCode(callSuper=false)
5. @JsonRootName(value="category")
6. public class DishCategory extends BaseEntity {
7. serialVersionUID = -7189824224534351030L;
8.
9. @Column
10. private String name;
11.
12. @Column
13. private String description;
14.
15.
16. @OneToMany
17. name="category_id",referencedColumnName="id")
18. <MealDish> dishes;
19. }
另外一个实体Bean为MealDish, 其代码为:
[html] view plain copy
1. @Entity
2. @Table(name = "dish")
3. @JsonRootName(value="dish")
4. //@Lazy(value=false)
5. public class MealDish extends BaseEntity {
6. serialVersionUID = -3982356728880195795L;
7.
8. @Column
9. private String name;
10.
11. @Column
12. private float price;
13.
14. name = "img_url")
15. private String imgUrl;
16.
17. 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
1. @Service
2. public class DishServiceImpl implements DishService {
3. @Transactional
4. @Override
5. <DishCategory> getDishCategory() {
6. return this.dishCategoryRepo.findAll();
7. }
8. ........
9. }
Repository相关的代码都是空代码,无实际的实现,这里再次忽略。
单元测试的代码内容:
[html] view plain copy
1. @Test
2. public void testDishes() throws JsonProcessingException {
3. mapper = new ObjectMapper();
4.
5. <DishCategory> categories = this.dishService.getDishCategory();
6.
7. for (DishCategory category : categories) {
8. // log.debug(String.valueOf(category.getDishes().get(0)));
9. }
10.
11. 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
1. @Entity
2. @Table(name="dish_category")
3. @Data
4. @EqualsAndHashCode(callSuper=false)
5. @JsonRootName(value="category")
6. public class DishCategory extends BaseEntity {
7. serialVersionUID = -7189824224534351030L;
8.
9. @Column
10. private String name;
11.
12. @Column
13. private String description;
14.
15.
16. fetch=FetchType.EAGER)
17. name="category_id",referencedColumnName="id")
18. <MealDish> dishes;
19. }
方法4的解释与说明:
这个设置选项:
spring.jpa.open-in-view=true
其实是之前的
openEntityManagerInViewInterceptor
,解决在Spring MVC与JPA之间Session的声明周期问题
5. 总结
核心问题在于解决延迟加载为及时加载,及时加载会消耗一定的资源,将其程序的性能,请注意这个问题。