问题:
最近在执行代码的时候比如说我查一条空的记录,然后修改状态之后保存,后面查空的记录还在,我刚开始以为是并发问题,但是后来发现是执行时间的问题,我这条修改记录的命令发出去了,但是数据库没来得及改,然后就是又被查询出来了,是事务提交的时间有延迟
解决办法是上手动事务
这样能保证代码执行完,反馈一个结果然后在继续执行
@Autowired
private DataSourceTransactionManager transactionManager;
try {
//手动开启事务
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus transactionStatus = transactionManager.getTransaction(def);
try {
giftTypeDao.decrDayRemainInventory(giftTypeDO.getId(), giftTypeDO.getDayRemainInventory());
//事务提交
transactionManager.commit(transactionStatus);
} catch (Exception e) {
//事务回滚
transactionManager.rollback(transactionStatus);
throw e;
}
} catch (Exception e) {
//处理异常
throw new ServiceException(ApiResponseCodeEnum.FAIL, "网络错误,请稍后再试!");
}