title: Can I deactivate Hibernate outside transactions to avoid LazyInitializationException
body: <h2><strong>EDIT</strong> - I have solved my specific problem with jackson/hibernate using the library <a href="https://github.com/FasterXML/jackson-module-hibernate" rel="nofollow">https://github.com/FasterXML/jackson-module-hibernate</a>. The solution was not the one I searched for here, but it is equally valid in my situation.</h2>
  
  <p>Original question:</p>
  
  <p>I have recently come across the infamous <code>org.hibernate.LazyInitializationException</code> when using Hibernate/Spring/Jackson. The problem for me occurs when jackson tries to serialize and object, finds an attribute that is a lazy-fetched value and tires to access it. I have read a lot of questions, posts and discussions about this but the proposed solution always seems to be a variant of two alternatives</p>
  
  <ul>
  <li>Make sure that the lazy attributes are loaded before the transaction ends.</li>
  <li>Configure jackson to ignore the attribute.</li>
  </ul>
  
  <p>I wonder if there is another solution because the fact is that when my service returns a Hibernate object with some attributes not initialized, then I want to display the object in that manner. Configuring jackson for the specific purpose seems to be a strategy where the presentation layer needs intricate knowledge of the database layer and that seems like a bad solution.</p>
  
  <p>The way I would like it to work from my initial look at the frameworks is that whenever a Hibernate entity is accessed outside a transaction, hibernate should not care about the object and it should act like a normal POJO. In essence:</p>
  
  <ol>
  <li>Start a transaction</li>
  <li>Perform CRUD operations on Hibernate managed objects.</li>
  <li>End the transaction and possibly return fetched/modified objects that can be used read/altered without events propagating to the underlying database.</li>
  </ol>
  
  <p>Example of desired behaviour:</p>
  
  <pre><code>//Start transaction
  MyEntity entity = entityManager.find(primaryKey, MyEntity.class);
  entity.getLazyLoadedFooList(); //Load the list from database
  //End transaction
  entity.getLazyLoadedBarList(); //Return null instead of throw LazyInitializationException
  </code></pre>
  
  <p>The basic idea is that the applications has a presentation, service and a DAO layer. The DAO layer is concerned with CRUD operations against the database. The Service layer wraps DAO methods in transactions and returns java objects that represent the data that was asked for. These objects are then available to to the presentation layer which converts them <em>as they are</em> to the desired format, in this case JSON.</p>
  
  <p>Two questions about this:</p>
  
  <ul>
  <li>Can it be done like I describe or in some similar fashion?</li>
  <li>Is it a good/bad idea?</li>
  </ul>