spring事务管理不起作用

ank*_*kit 5 java configuration spring hibernate transactions

我在春天使用程序化事务管理,现在我已经切换到声明式事务管理.

SessionFactory的

<beans:bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource" />
        <beans:property name="packagesToScan" value="com.hcentive.cig.domain" />
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
                <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                </beans:prop>
                <beans:prop key="hibernate.show_sql">true</beans:prop>
                <beans:prop key="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean> 
Run Code Online (Sandbox Code Playgroud)

事务管理

<beans:bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory">
            <beans:ref bean="sessionFactory" />
        </beans:property>
    </beans:bean>
Run Code Online (Sandbox Code Playgroud)

现在如果运行我的代码

@Override
    @Transactional
    public Request saveRequest(Request request) {
        sessionFactory.getCurrentSession().save(request);
        return request;
    }
Run Code Online (Sandbox Code Playgroud)

如果没有活动事务,我会收到异常保存无效

如果我删除下面的行

<beans:prop key="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</beans:prop>
Run Code Online (Sandbox Code Playgroud)

我明白了

没有配置CurrentSessionContext!

Vla*_*cea 2

你绝对不需要这个设置:

<beans:prop key="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</beans:prop>
Run Code Online (Sandbox Code Playgroud)

Spring事务管理层应该将Hibernate Session绑定到当前运行的线程。

设置没问题,唯一可能导致此问题的原因来自您的以下声明:

不,它是从服务层调用的,而且我也尝试将@事务性移动到服务层

您需要公开此方法:

Request saveRequest(Request request);
Run Code Online (Sandbox Code Playgroud)

通过 Service 接口,您可以将其注入到任何其他组件(Web 或其他服务层 bean)中。

为了验证这一点,您可以在方法实现中放置一个调试断点,并在调用堆栈中saveRequest查找TransactionInterceptor 。如果它不存在,那么 Spring 无法将您的方法调用包装到事务方面处理逻辑中。