title: How to test if Hibernate Session is open?
body: <p>I am facing Transaction errors such:</p>
  
  <blockquote>
    <p>org.hibernate.LazyInitializationException: failed to lazily initialize
    a collection of role:
    app.Parent.children, could
    not initialize proxy - no Session</p>
  </blockquote>
  
  <p>Here on <code>parent.getChildren().size()</code>.</p>
  
  <p>But I do have an <code>@Transactional</code> on <code>@Service</code> methods:</p>
  
  <ul>
  <li>1 transaction on <code>createFactory()</code> to create a factory and give the entitymanager</li>
  <li>1 transaction on <code>create()</code> to create the entity</li>
  </ul>
  
  <pre class="lang-java prettyprint-override"><code>@Path("api/parents")
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  @Controller
  public class ParentResource {
  
      @Autowired
      private ParentService parentService;
  
      @POST
      public Parent create(Parent parent) {
          ParentFactory parentFactory = parentService.createFactory(parent);
          return parentService.create(parent);
      }
  
  }
  
  @Service
  public class ParentService {
  
      @PersistenceContext
      private EntityManager em;
  
      @Transactional
      public ParentFactory createFactory(Parent parent) {
          return new ParentFactory(parent, em);
      }
  
      @Transactional
      public Parent create(ParentFactory parentFactory) {
          return parentFactory.create();
      }
  
  }
  
  // No Transactional annotation
  public class ParentFactory {
  
      private Parent parent;
      private EntityManager em;
  
      public ParentFactory(Parent parent, EntityManager em) {
          this.parent = parent;
          this.em = em;
      }
  
      public parent create() {
          if(parent.getChildren().size() &lt; 3) { // Exception here
              em.persist(this.parent);
          }
      }
  
  }
  </code></pre>
  
  <p>I'd like to be able to test when my Hibernate Session is alive or not, so that I can check when it's lost and why.</p>
  
  <p>Thanks !</p>