回滚已检查和未检查的异常上的事务

时间:2011-11-05 18:45:05

标签: spring postgresql jdbctemplate spring-jdbc

我正在使用Spring JDBC Template和PostgreSQL。以下是我的配置 数据源和交易设置:

<bean id="databasePropertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/config/database.properties" />

    <bean id="dataSource"
          class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:driverClassName="${database.driverClassName}"
          p:url="${database.url}"
          p:username="${database.username}"
          p:password="${database.password}" />

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

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

在我的业务层中,我正在执行以下操作:

@Transactional(rollbackFor=Exception.class)
@RequiresPermissions("hc:patient_createInvoice")
public Long createInvoice(Invoice invoice, List<InvoiceItem> items) throws ValidationException, NetAmountMismatchException, PatientInvoiceException
{
       try{
            dao1.insert(invoice);
       }
       catch(DataAccessException x){
            throw new PatientInvoiceException(x);
       }

       try{
            somevalidation(invoiceItem);    // Causes validation exception
            dao2.insert(invoiceItems);
       }
       catch(DataAccessException x){
       throw new PatientInvoiceException(x);
   }
}

这样的事情。我需要的是,无论何时抛出此方法的任何异常(已检查或未检查),都应该滚动到目前为止执行的所有数据库更新。

目前的代码不会发生这种情况。

实际上我错过了什么?

1 个答案:

答案 0 :(得分:2)

默认情况下,Spring仅回滚未经检查的异常的事务。来自Spring reference manual

  

Spring Framework的事务基础结构代码仅在运行时未经检查的异常情况下标记用于回滚的事务; [...]从事务方法抛出的已检查异常不会导致在默认配置中回滚。

但是,您也可以将Spring配置为回滚以检查已检查的异常,例如:

<tx:advice id="txAdvice">
    <tx:attributes>
        <tx:method name="*" rollback-for="ValidationException, NetAmountMismatchException, PatientInvoiceException" />
    </tx:attributes>
</tx:advice>