编程式事务配置
@Transactional方式
直接在service方法加入注释即可
@Transactional public int txUpdateUsersWhenException() { Merchant merchant=new Merchant(); merchant.setId(1); merchant.setEnName("333"); int affectedCount = super.update(merchant); System.out.println(affectedCount ); int i = 1 / 0; // 抛出运行时异常,事务回滚 return 0; }
TransactionTemplate方式
@Autowired(required = false)TransactionTemplate txTemplate;public int txUpdateUsersWhenExceptionViaTxTemplate() { int retVal = txTemplate.execute(new TransactionCallback() { @Override public Integer doInTransaction(TransactionStatus status) { // 事务操作 User user = new User(9, "Before exception"); int affectedCount = mapper.updateUser(user); // 因后面的异常而回滚 User user2 = new User(10, "After exception"); int i = 1 / 0; // 抛出运行时异常并回滚 int affectedCount2 = mapper.updateUser(user2); // 未执行 if (affectedCount == 1 && affectedCount2 == 1) { return 1; } return 0; } }); return retVal;}