1、启动类加上@EnableTransactionManagement

@SpringBootApplication
@EnableEurekaClient //本服务启动后会自动注册进eureka服务中
@EnableDiscoveryClient //服务发现
@EnableCircuitBreaker//对hystrixR熔断机制的支持
@EnableTransactionManagement
@EnableFeignClients(basePackages= {"com.atguigu.springcloud"})
public class ProjectProvider8002_basefile_Hystrix_App
{
	public static void main(String[] args)
	{
		SpringApplication.run(ProjectProvider8002_basefile_Hystrix_App.class, args);
	}
}

2、事务注解 @Transactional(rollbackFor = Exception.class)

@Transactional(rollbackFor = Exception.class)
public Result deleteNavigation(String navigationUuid) {
    logMsg.setOperation("删除导航:deleteNavigation");
    Result result = new Result();
    try {
        //删除导航表数据
        boolean flag = navigationDao.deleteNavigation(navigationUuid);
       if (!flag){
           throw new Exception("删除导航数据失败!");
       }
       //根据导航栏uuid获取子导航的uuid集合
        List<String> moduleList = navigationDao.getMuduleListByNavigationUuid(navigationUuid);
       if (moduleList.size()>0){
           //删除子模块和款式的关联关系表
           boolean linkedFlag = navigationDao.deleteNavigationChildAndDeviceType(moduleList);
           if (!linkedFlag){
               throw new Exception("删除子模块和款式的关联关系表失败!");
           }
           boolean moduleFlag = navigationDao.deleteModuleByNavigationUuid(moduleList);
           if (!moduleFlag){
               throw new Exception("删除子模块失败!");
           }
       }
        //封装返回结果
        result.setType("deleteNavigation_ACK");
        result.setResult(flag);
        result.setMsg("删除导航成功");
        return result;
    } catch (Exception e) {
        e.printStackTrace();
        result.setResult(false);
        result.setMsg("删除导航异常");
        result.setCode(Result.Code.UnKnowError.value());
        //@Transactional和try catch捕获异常会让注解失效
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return result;
    }
}
如果三个表中有一个表删除失败返回false或者产生异常,都会产生事务回滚,将之前添加或者修改的数据进行回滚。

特别提醒:
正常情况下加注解@Transactional和try catch捕获异常会让注解失效
解决办法就是在catch语句块中添加TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐