title: Howto use Hibernate StatelessSession in SpringBatch Writer
body: <p>is there a way to use a <code>StatelessSession</code> within a spring-batch Writer which is taking part of the current spring-batch JDBC-Transaction and Hibernate-Transaction?</p>
  
  <p>I tried</p>
  
  <pre><code>public class MyWriter implements ItemWriter&lt;SomeClass&gt; {
      @Override
      public void write(final List&lt;? extends SomeClass&gt; items) throws Exception {
          StatelessSession session = sessionFactory.openStatelessSession();
          Transaction tx = session.beginTransaction();
          for(SomeCLass item : items){
              session.insert(item);
          }
          tx.commit();
          session.close();
      }
  }
  </code></pre>
  
  <p>but actually it is creating a new HibernateSession outside from the session handled by spring-batch. How to get the <code>StatelessSession</code> being attached to the current statefull-<code>Session</code>.</p>
  
  <p>Background: I would love to use a stateless-session because the method <code>myStatefullHibernateSession.save(item)</code> is loading associated objects that are also not part of the session. I am doing so in order to minimize the number of sqls created and in my batch-environment this is saving a lot cpu-costs and is reducing runtime while processing millions  of data-records.</p>
  
  <p>Hibernate: 3.6.10<br/>
  Spring-Batch: 2.2.0</p>
  
  <p><strong>edit:</strong> With the help of <code>axtavt</code> I got it working to use the same JDBC-Transaction but I am using in addition the hibernate property <code>hibernate.jdbc.batch_size</code> which causes the following observation:</p>
  
  <ol>
  <li>If using <code>beginTransaction</code> and <code>commit</code> on the created <code>StatelessSession</code> the transaction-control of spring-batch is not working any more (later exceptions in the writer wont rollback)</li>
  <li>If not creating a hibernate-transaction on the <code>StatelessSession</code> the transaction-control of spring-batch will work but a spring-batch-commit will not commit the insert/update/delete-statements lying in the <code>BatchingBatcher</code> of Hibernate in the <code>StatelessSession</code>.</li>
  </ol>
  
  <p>To sum it up: I just need a <code>StatelessSession</code> instead of the standard-hibernate stateful-<code>Session</code> in my writer.</p>