2013-09-16 63 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

相关问题