✅P281_商城业务-订单服务-保存订单数据
大约 1 分钟
保存订单和订单项数据
**cfmall-order/src/main/java/com/gyz/cfmall/order/service/impl/OrderServiceImpl.java**
见: this.saveOrder(order);
添加@Transactional(rollbackFor = Exception.class)
注解,保证保存订单和订单项信息处于一个事务,有异常回滚数据
@Transactional(rollbackFor = Exception.class)
@Override
public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo) {
SubmitOrderResponseVo responseVo = new SubmitOrderResponseVo();
MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();
String token = orderSubmitVo.getOrderToken();
//脚本执行的返回结果: 0-代表令牌校验失败, 1-代表令牌成功删除即成功
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
//Arg1:用DefaultRedisScript的构造器封装脚本和返回值类型; Arg2:用于存放Redis中token的key;Arg3:用于比较的token,即浏览器存储的token
//令牌的验证和删除必须保证原子性
Long response = redisTemplate.execute(
new DefaultRedisScript<>(script, Long.class),
Collections.singletonList(OrderConstant.USER_ORDER_TOKEN_PREFIX.toString() + memberResponseVo.getId()),
token);
if (response != null && response == 0) {
responseVo.setCode(1);
return responseVo;
} else {
//TODO:令牌校验成功,去创建订单,校验价格,所库存
submitVoThreadLocal.set(orderSubmitVo);
//1、创建订单、订单项等信息
OrderCreateTo order = this.createOrder();
BigDecimal payAmount = order.getOrder().getPayAmount();
double substractValue = 0.01;
if (Math.abs(orderSubmitVo.getPayPrice().subtract(payAmount).doubleValue()) < substractValue) {
//保存订单和订单项信息
this.saveOrder(order);
} else {
responseVo.setCode(2);
return responseVo;
}
}
return null;
}
private void saveOrder(OrderCreateTo order) {
//获取订单信息
OrderEntity orderEntity = order.getOrder();
orderEntity.setModifyTime(new Date());
orderEntity.setCreateTime(new Date());
//保存订单
this.baseMapper.insert(orderEntity);
//获取订单项信息
List<OrderItemEntity> orderItems = order.getOrderItems();
//批量保存订单项数据
orderItemService.saveBatch(orderItems);
}