发生RuntimeException时不会回滚事务

时间:2018-12-04 08:20:17

标签: java spring spring-transactions transactional

当方法update2发生异常时,我想更新合同1,并收缩合同7。但是,这两个合同都保存了成功。

如果我将propagation中的update2REQUIRES_NEW更改为REQUIRED,则会抛出异常"Transaction silently rolled back because it has been marked as rollback-only"

我该如何实现?

@Service
public class UserService {
    @Autowired
    private ContractRepo contractRepo;

    @Autowired
    ContractService contractService;

    @Transactional(value = "transactionManager2")
    public void update1() {
        CONTRACT con1 = contractRepo.findById("1120180001").get();
        con1.setCONTRACT_DATE(new Date());
        contractRepo.save(con1);

        CONTRACT con7 = contractRepo.findById("1120180007").get();
        try {
            contractService.update2(con7);
        } catch (RuntimeException ex) {
            System.out.println("Exception when calling update2 " + ex.getMessage());
        }
    }
}

@Service
public class ContractService {
    @Autowired
    private ContractRepo contractRepo;

    @Transactional(value = "transactionManager2", propagation = Propagation.REQUIRES_NEW)
    public void update2(CONTRACT con) {
        con.setCONTRACT_DATE(new Date());
        contractRepo.save(con);
        throw new RuntimeException("RuntimeException update2: test for rollback");
    }
}

调用更新方法

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Autowired
    private UserService userService;

    @Override
    public void run(String... args) throws Exception {
        userService.update1();
    }
}

0 个答案:

没有答案