zoukankan      html  css  js  c++  java
  • JPA中事务回滚的问题

     我的项目使用的是Spring Boot,Spring Data JPA 其中Spring已经封装好了事务,在注解@Transactional中,自动执行事务,出异常自动回滚,但在使用的时候会遇到一些问题:

    在多个方法中使用@Transactional,其中一个方法运行时候报错,但是数据却插进去了,但是其他两个方法没有;有时候抛了异常,却不会回滚;方法嵌套的时候执行报错……

      查阅了一些资料后,得知是没有正确使用Spring的@Transactional。

      下面借用我查到的别人的博客中的例子来说明Spring的@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);
        }
        
        
        
    }
    

      

    对于常用的Spring的@Transactional的总结如下:

    1、异常在A方法内抛出,则A方法就得加注解
    2、多个方法嵌套调用,如果都有 @Transactional 注解,则产生事务传递,默认 Propagation.REQUIRED
    3、如果注解上只写 @Transactional  默认只对 RuntimeException 回滚,而非 Exception 进行回滚
    4、如果要对 checked Exceptions 进行回滚,则需要 @Transactional(rollbackFor = Exception.class)
  • 相关阅读:
    Unity NGUI 2D场景添加按钮
    EaseType缓动函数
    在没有网络的情况下用安卓手机和数据线让台式电脑上网
    面向对象编程
    static与C#中的static
    C#基础
    iSensor APP 之 摄像头调试 OV5642
    iSensor APP 之 摄像头调试 OV9655
    USB3.0之高速视频传输测试 双目相机(mt9p031、mt9m001)带宽高达300M测试 配合isensor测试 500万像素15fps
    模拟摄像头解码模块最新测试 TVP5150模块 FPGA+SDRAM+TVP5150+VGA 实现PAL AV输入 VGA视频输出
  • 原文地址:https://www.cnblogs.com/Andrew520/p/12144362.html
Copyright © 2011-2022 走看看