title: Understanding transaction session with lazy loading in Spring JPA Hibernate
body: <p>I would like to get some clarification regarding lazy loading and session boundaries etc.</p>
  
  <p>My code structure is as follows</p>
  
  <pre><code>@Entity
  
  class A {
  
  ....
  
    @OneToOne(fetch=LAZY)
    private B b;
  
    ..
  }
  
  @Entity
  class B {
  
   private id;
  
   private name;    
  
  }
  
  @Transactional(SUPPORTS)
  ADao {
    A findById(int id);  
  }
  
  @Transactional(SUPPORTS)
  LayerDB {
  
      A getAForId(int i) {
        return adao.findById(i);
      }
  
  }
  
  //Note that there is no transactional attribute here
  LayerB {
  
     public boolean doSomethingWithAandB(int aId) {
      A a = LayerDB.getAForId(aId);
      if(a.getB().getName().equals("HIGH"))
       return true;
      return false;
     }
  
  }
  
  //start transaction here
  @Transaction(REQUIRED)
  LayerC {
  
      LayerB layerb;
  
      private handleRequest(int id) {
  
         layerb.doSomethingWithAandB(id);
  
      }
  }
  </code></pre>
  
  <p>Now when we try to access B in entity A within the method</p>
  
  <pre><code>doSomethingWithAandB
  </code></pre>
  
  <p>Am getting a lazy initialization exception when trying to access B.</p>
  
  <p>Even though the method is within the transaction created in LayerC, still i get the following exception</p>
  
  <pre><code>Exception : org.hibernate.LazyInitializationException: could not initialize proxy - no Session
  </code></pre>
  
  <p>But on changing the following two methods as :</p>
  
  <pre><code>@Transactional(SUPPORTS)
  LayerDB {
  
     A getAForId(int i) {
        A a = adao.findById(i);
        a.getB().getName();
        return a;
      }
  
  }
  
  //Note that there is no transactional attribute here
  LayerB {
  
     public boolean doSomethingWithAandB(int aId) {
       A a = LayerDB.getAForId(aId);
       if(a.getB().getName().equals("HIGH"))
       return true;
      return false;
    }
  
  }
  </code></pre>
  
  <p>Why is it not using the transaction / session created in LayerC ?</p>
  
  <p>Even though we have SUPPORTS on the DBLayer, is it creating a separate 'session'.</p>
  
  <p>Any pointers for proper understand would help me a great deal.</p>
  
  <p>Thank you.</p>