Spring LazyInitializatoinException
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring LazyInitializatoinException相关的知识,希望对你有一定的参考价值。
今天做project创建了一个新的类A,这个新类包含了一个另外一个类B的Set。B类包含了另外一个C类的集合。。。
1 public class A{ 2 3 @Id 4 5 int id; 6 7 @OneToMany(fetch=FetchType.Lazy) 8 9 Set<B> bInstances; 10 11 12 public Set<B> getBInstances(){ 13 14 return bInstances; 15 16 } 17 18 } 19 20 21 public class B{ 22 23 @Id 24 25 int id; 26 27 @OneToMany(fetch=FetchType.Lazy) 28 29 Set<C> cInstances; 30 31 }
I define a get function with A‘s aId and B‘s bId as input parameters in A‘s facade and it should return B‘s instance with the exact bId in A‘s instance with aId.
1 @Component 2 public class AFacade{ 3 @Autowired 4 AService aService; 5 public B getBInstance(int aId, int bId){ 6 return aService.getBInstance(aId, bId); 7 } 8 9 In A‘s Service class 10 11 @Component 12 public class AService{ 13 14 @Autowired 15 ADao aDao; 16 17 @Transactional 18 public A getAInstance(int aId, int bId){ 19 for(B b: aDao.getAInstance(aId).getBInstances()){ 20 if( b.getId()==bId){ 21 return b; 22 } 23 } 24 return null; 25 } 26 }
With the code above, I always get the LazyInitializationException. Finally, I figure out the reason. The Transaction ends after AService.getAInstance returns. To fix it, I should move the @Transactioanl annotation to the facade class‘s getBInstance function.
以上是关于Spring LazyInitializatoinException的主要内容,如果未能解决你的问题,请参考以下文章
Spring全家桶笔记:Spring+Spring Boot+Spring Cloud+Spring MVC
学习笔记——Spring简介;Spring搭建步骤;Spring的特性;Spring中getBean三种方式;Spring中的标签
Spring框架--Spring事务管理和Spring事务传播行为