2013-09-16 62 views
18

我有一個使用Hibernate 4和Spring Transactions的Spring 3.2應用程序。所有的方法工作得很好,我可以正確訪問數據庫來保存或檢索實體。 然後,我介紹了一些多線程,並且因爲每個線程訪問到DB我是從休眠收到以下錯誤:Spring Transactions和hibernate.current_session_context_class

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions 

我從我已經添加<prop key="hibernate.current_session_context_class">thread</prop>我的Hibernate配置網絡閱讀,但現在每次我嘗試訪問分貝我得到:

org.hibernate.HibernateException: saveOrUpdate is not valid without active transaction 

但是我的服務方法與@Transactional註釋,以及所有被的<prop key="hibernate.current_session_context_class">thread</prop>的添加之前工作的罰款。

爲什麼沒有事務,雖然方法用@Transactional註釋?我怎麼解決這個問題?

這裏是我的Hibernate配置(包括會話上下文屬性):

<?xml version="1.0" encoding="UTF-8"?> 
<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"> 

<!-- Hibernate session factory --> 
<bean 
    id="sessionFactory" 
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" > 
    <property name="dataSource" > 
     <ref bean="dataSource" /> 
    </property> 
    <property name="hibernateProperties" > 
     <props> 
      <prop key="hibernate.hbm2ddl.auto">create</prop> 
      <prop key="hibernate.dialect" >org.hibernate.dialect.MySQLDialect</prop> 
      <prop key="hibernate.show_sql">true</prop> 
      <prop key="hibernate.current_session_context_class">thread</prop> 
     </props> 
    </property> 
    <property name="annotatedClasses" > 
     <list> 
      ... 
     </list> 
    </property> 
</bean> 

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
    <property name="sessionFactory" ref="sessionFactory"/> 
</bean> 

<tx:annotation-driven transaction-manager="transactionManager"/> 

回答

31

當使用從未混亂與周圍的hibernate.current_session_context_class財產春春管理事務除非您使用JTA。

Spring將默認設置自己的CurrentSessionContext實現(SpringSessionContext),但是如果您自己設置它,情況就不會如此。基本上打破了正確的交易整合。

更改此設置的唯一原因是每當您想使用JTA託管事務時,您都必須設置此項以正確地與JTA集成。

+0

好的,我恢復了舊的配置,但現在,我該如何解決'org.hibernate.HibernateException:非法嘗試將一個集合與兩個打開的會話關聯起來,並且多線程?基本上我必須使用線程,並且他們都嘗試對包含集合的同一個對象執行'save()'操作。也許我必須避免這種情況,只做其中的一種? – user1781028

+1

爲什麼你有一個單一的對象,這是由多個線程保存。 –

+0

好吧,我刪除了其中一個保存操作。但是,如果由於某些特殊原因,我真的需要它們兩個呢? – user1781028

相關問題