springboot手动回滚事务

1.开启事务@EnableTransactionManagement

@SpringBootApplication
@EnableTransactionManagement
@MapperScan("")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2.标记当前方法要使用事务@Transactional

@Override
    @Transactional
    public Integer setAllPeriod(Map<String, Object> map) {
        List<Integer> idList= (List<Integer>) map.get("customerIds");
        //定义锚点
        Object savePoint=TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            for (Integer integer : idList) {
                TCustomerManagement customerManagement = tCustomerManagementMapper.selectByPrimaryKey(integer);
                customerManagement.setOverdueGraceDate((Integer) map.get("overdueGraceDate"));
                tCustomerManagementMapper.updateByPrimaryKey(customerManagement);
            }
            return 1;
        } catch (Exception e) {
            //手动回滚事务
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            return 0;
        }
    }

3.定义锚点

Object savePoint=TransactionAspectSupport.currentTransactionStatus().createSavepoint();

4.回滚到锚点

TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);

你可能感兴趣的:(springboot)