springboot注解异常处理事务回滚

版权声明: https://blog.csdn.net/qq_27721169/article/details/82023849

1、开始事务支持

@EnableTransactionManagement // 开启注解事务管理,等同于xml配置文件中的 <tx:annotation-driven />
@SpringBootApplication(scanBasePackages = {"com.xxx.xxx.xxx", "com.xxx.xxx.xxx"})
@MapperScan("com.xxx.xxx.xxx.dao")
@EnableJms
@EnableTransactionManagement
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

2、在需要使用事务的方法上增加注解

@Service
public class xxxx{
    
    @Transactional
    public void xxx(){
        try {
                if(false){
                    throw new Exception("事物回退");
                }
                    
                } catch (Exception e) {
                    e.printStackTrace();
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
    }
}

或者可以自定义异常

public class zhy extends RuntimeException  {

    public zhy(String message) {
        super(message);
    }
}
@Service
public class xxxx{
    
    @Transactional
    public void xxx(){
       
                if(false){
                    throw new zhy("事物回退");
                }    
             
    }
}

 

展开阅读全文

没有更多推荐了,返回首页