@Transactional 对于 Spring 中的任何异常

@Transactional for any Exceptions in Spring

我正在寻找在其中一种服务方法上使用 @Transactional。但是,当发生异常时,事务不会回滚。我对 @Transactional(rollbackFor=Exception.class) 进行了同样的尝试。我的代码如下:-

    @Override
    @Transactional(rollbackFor=Throwable.class)
    public boolean addUser(User user) throws Exception{
        boolean userAdded = userDao.addUser(user);                  
        boolean userRegistrationRecorded = userDao.recordUserRegistraionDetails(user);      
        return true;
    }

我读了很多帖子,每个人都说 Spring 只处理 RuntimeException,除了 RmiException 之外没有检查 Exception。我需要一个适用于任何类型 Exception 的解决方案。有人建议我写自己的注释,而其他人建议将 TransactionManager 作为 applicationContext.xml 文件的一部分。详细的解决方案肯定会帮助我。

顺便说一句,我正在使用 Spring JdbcTemplate。我观察到的奇怪的事情是,虽然 Spring 引发的 Exceptions 是 RuntimeExceptions,但事务没有被回滚。我试图通过在上述场景中添加相同的 User 来提高 Exception

我的applicationContext.xml如下:-

<context:component-scan base-package="org.chaperone.services.security.*" />

    <context:annotation-config />

    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="propertyPlaceholderConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="searchSystemEnvironment" value="true" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="${DATABASE_URL}" />
        <property name="username" value="${DATABASE_USER_NAME}" />
        <property name="password" value="${DATABASE_PASSWORD}" />
    </bean>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

使用 @Transactional 注释提供的易用性在 link

中得到了最好的说明

你必须添加:

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