title: Alternative to sharing hibernate session between threads
body: <p>I am working with Spring 3.0.7 / Hibernate 3.5.0.
  I have some code that works with hibernate entity. It works ok. The problem occurs, when I try to make integration test for this code. Below is the scheme of how code is laid out with regards to transactions, just to give an idea what the issus is about.</p>
  
  <pre><code>class EntityDAOImpl implements EntityDAO&lt;T&gt;
  {
      public T save(T entity)
      {
          getHibernateTemplate().saveOrUpdate(entity);
      }
  }
  class EntityManagerImpl : implements EntityManager
  {
      //EntityDAO dao;
      @Transactional
      public Entity createEntity()
      {
          Entity entity = dao.createNew();
          //set up entity
          dao.save(entity);
      }
      public Entity getFirstEntity()
      {
          return dao.getFirst();
      }
  }
  </code></pre>
  
  <p>The code is run across 2 threads.</p>
  
  <pre><code>Thread1:
      //EntityManager entityManager
      entityManager.createEntity();
      //enity was saved and commited into DB
      Thread thread2 = new Thread();
      thread2.start();
      //...
      thread2.join();
      ...
  Thread2:
      //since entity was commited, second thread has no problem reading it here and work with it
      Entity entity = entityDao.findFirst();
  </code></pre>
  
  <p>Now I have also an integration test to this code. And here where lies the problem. Transactions for this test are rollbacked, since I don't want to see any changes in the database after it is done.</p>
  
  <pre><code>@TransactionConfiguration(transactionManager="transactionManagerHibernate", defaultRollback=true)
  public class SomeTest
  {
      @Transactional
      public void test() throws Exception
      {
          //the same piece of code as described above is run here. 
          //but since entityManager.createEntity(); doesn't close transaction, 
          //Thread2 will never find this entity when calling entityDao.findFirst()!!!!!
      }
  }
  </code></pre>
  
  <p>I understand that sharing a hibernate session between threads is not a good idea.
  What approach would you recommend to handle this situation?</p>
  
  <p>My first thought was try to simplify and avoid threading - but threading helps me spair memory, otherwise I would have to hold huge chunks of data in memory.</p>