首页 > 代码库 > Spring LazyInitializatoinException

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 As 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