JPA的事务注解@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
         * 
         * 
         * 
         */
复制代码

 

posted @   远哥  阅读(25760)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示