@Transactional注解

项目开发过程中,如果您的项目中使用了Spring的@Transactional注解,有时候会出现一些奇怪的问题,例如:

 

明明抛了异常却不回滚?

嵌套事务执行报错?

...等等

 

很多的问题都是没有全面了解@Transactional的正确使用而导致的,下面一段代码就可以让你完全明白@Transactional到底该怎么用。

 

直接上代码,请细细品味

复制代码
@Service
public class SysConfigService {

    @Autowired
    private SysConfigRepository sysConfigRepository;
    
    public SysConfigEntity getSysConfig(String keyName) {
        SysConfigEntity entity = sysConfigRepository.findOne(keyName);
        return entity;
    }
    
    public SysConfigEntity saveSysConfig(SysConfigEntity entity) {
        
        if(entity.getCreateTime()==null){
            entity.setCreateTime(new Date());
        }
        
        return sysConfigRepository.save(entity);
                
    }
    
    @Transactional
    public void testSysConfig(SysConfigEntity entity) throws Exception {
        //不会回滚
        this.saveSysConfig(entity);
        throw new Exception("sysconfig error");
        
    }
    
    @Transactional(rollbackFor = Exception.class)
    public void testSysConfig1(SysConfigEntity entity) throws Exception {
        //会回滚
        this.saveSysConfig(entity);
        throw new Exception("sysconfig error");
        
    }
    
    @Transactional
    public void testSysConfig2(SysConfigEntity entity) throws Exception {
        //会回滚
        this.saveSysConfig(entity);
        throw new RuntimeException("sysconfig error");
        
    }
    
    @Transactional
    public void testSysConfig3(SysConfigEntity entity) throws Exception {
        //事务仍然会被提交
        this.testSysConfig4(entity);
        throw new Exception("sysconfig error");
    }
    
    @Transactional(rollbackFor = Exception.class)
    public void testSysConfig4(SysConfigEntity entity) throws Exception {
        
        this.saveSysConfig(entity);
    }
    
    
    
}
复制代码

 

总结如下:

复制代码
        /**
         * @Transactional事务使用总结:
         * 
         * 1、异常在A方法内抛出,则A方法就得加注解
         * 2、多个方法嵌套调用,如果都有 @Transactional 注解,则产生事务传递,默认 Propagation.REQUIRED
         * 3、如果注解上只写 @Transactional  默认只对 RuntimeException 回滚,而非 Exception 进行回滚
         * 如果要对 checked Exceptions 进行回滚,则需要 @Transactional(rollbackFor = Exception.class)
         * 
         * org.springframework.orm.jpa.JpaTransactionManager
         * 
         * org.springframework.jdbc.datasource.DataSourceTransactionManager
         * 
         * org.springframework.transaction.jta.JtaTransactionManager
         * 
         * 
         * 
         */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值