title: Spring Transactions and hibernate.current_session_context_class
body: <p>I have a Spring 3.2 application that uses Hibernate 4 and Spring Transactions. All the methods were working great and I could access correctly the database to save or retrieve entities. 
  Then, I introduced some multithreading, and since each thread was accessing to db I was getting the following error from Hibernate:</p>
  
  <pre><code>org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
  </code></pre>
  
  <p>I read from the web that I've to add <code>&lt;prop key="hibernate.current_session_context_class"&gt;thread&lt;/prop&gt;</code> to my Hibernate configuration, but now every time I try to access the db I get: </p>
  
  <pre><code>org.hibernate.HibernateException: saveOrUpdate is not valid without active transaction
  </code></pre>
  
  <p>However my service methods are annotated with <code>@Transactional</code>, and all was working fine before the add of <code>&lt;prop key="hibernate.current_session_context_class"&gt;thread&lt;/prop&gt;</code>.</p>
  
  <p>Why there is no transaction although the methods are annotated with @Transactional? How can I solve this problem?</p>
  
  <p>Here is my Hibernate configuration (including the session context property):</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"&gt;
  
  &lt;!-- Hibernate session factory --&gt;
  &lt;bean
      id="sessionFactory"
      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" &gt;
      &lt;property name="dataSource" &gt;
          &lt;ref bean="dataSource" /&gt;
      &lt;/property&gt;
      &lt;property name="hibernateProperties" &gt;
          &lt;props&gt;
              &lt;prop key="hibernate.hbm2ddl.auto"&gt;create&lt;/prop&gt; 
              &lt;prop key="hibernate.dialect" &gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt;
              &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt;
              &lt;prop key="hibernate.current_session_context_class"&gt;thread&lt;/prop&gt;  
          &lt;/props&gt;
      &lt;/property&gt;   
      &lt;property name="annotatedClasses" &gt;
          &lt;list&gt;
              ...
          &lt;/list&gt;
      &lt;/property&gt; 
  &lt;/bean&gt;
  
  &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt;
      &lt;property name="sessionFactory" ref="sessionFactory"/&gt;
  &lt;/bean&gt;
  
  &lt;tx:annotation-driven transaction-manager="transactionManager"/&gt;
  </code></pre>
  
  <p></p>