Spring @Transactional annotation 不回滚

1【问题重现】

基于annotation配置,使用

org.springframework.web.WebApplicationInitializer

启动的web app, IoC容器继承自

org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter

而不使用传统的在web.xml 配置方式。

加上一下注解:

 

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.richard.wu")
@PropertySource("classpath:jdbc.properties")
@EnableTransactionManagement //事物注解
public class AppConfig extends WebMvcConfigurerAdapter {


}



在service类加上@Transactional后故意在2 update操作之间抛出一个

java.lang.ArithmeticException

 那么问题来了,检验发现第一个update 操作居然没有被回滚!!!

【解决】

仔细看了文档发现spring 的@Transactionl 仅仅在

RunTimeException

才回滚,所以为了让他对所有Exception回滚,必须这样写:

@Transactional(propagation= Propagation.REQUIRED, rollbackFor=Exception.class, readOnly=false)

关键是rollbackFor这个参数。但是改了之后发现还是不能如期回滚,百思不得姐,后来突然想到既然@Transactionl是通过异常类型来触发回滚的,然么关键就是要有异常从方法里面传递出来,再看看代码里面已经把异常部分用try catch住了,恍然大悟,赶紧解除try catch块,果然就ok了。又或者在catch到Exception后再次抛出也是可以的:

try {
        //update 1
        //exception occur here
        //update 2
    }catch (SQLException e){
        throw new SQLException( "出现SQL异常,回滚操作1");
    }

 

 

 

 

 

你可能感兴趣的:(spring,transactional)