Spring Transactions和hibernate.current_session_context_class

use*_*028 21 spring hibernate hibernate-session spring-transactions

我有一个使用Hibernate 4和Spring Transactions的Spring 3.2应用程序.所有方法都运行良好,我可以正确访问数据库以保存或检索实体.然后,我介绍了一些多线程,并且由于每个线程都访问了db,我从Hibernate收到以下错误:

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
Run Code Online (Sandbox Code Playgroud)

我从网上读到我要添加<prop key="hibernate.current_session_context_class">thread</prop>到我的Hibernate配置中,但是现在每次我尝试访问db时都会得到:

org.hibernate.HibernateException: saveOrUpdate is not valid without active transaction
Run Code Online (Sandbox Code Playgroud)

但是我的服务方法是注释的@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"/>
Run Code Online (Sandbox Code Playgroud)

M. *_*num 34

当使用Spring和Spring管理的事务时,永远不要乱用hibernate.current_session_context_class属性,除非您正在使用JTA.

Spring默认会设置自己的CurrentSessionContext实现(SpringSessionContext),但是如果你自己设置它,情况就不会如此.基本上打破了正确的事务集成.

更改此设置的唯一原因是,只要您想使用JTA托管事务,就必须将其设置为与JTA正确集成.

  • JTA托管交易和春季托管交易有什么区别? (3认同)