zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    python基础——返回函数
    python基础——sorted()函数
    python基础——filter函数
    python基础——map/reduce
    python基础——高阶函数
    python基础——迭代器
    python——生成器
    轻量级文本编辑器,Notepad最佳替代品:Notepad++
    python网络编程
    如何检测远程主机上的某个端口是否开启?
  • 原文地址:https://www.cnblogs.com/xinqiwm2010/p/6847745.html
Copyright © 2011-2022 走看看