今天依旧学习了黑马的瑞吉外卖,以下是我跟着视频学习写的代码,关于生成订单和订单明细表:
@Transactional public void submit(Orders orders) { //获得当前用户id Long currentId = BaseContext.getCurrentId(); //查询当前用户的购物车数据 LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>(); lqw.eq(ShoppingCart::getUserId,currentId); List<ShoppingCart> list = shoppingCartService.list(lqw); if(list == null || list.size() == 0){ throw new CustomException("购物车为空,无法完成订单"); } //查询用户数据 User user = userService.getById(currentId); //查询地址数据 Long addressBookId = orders.getAddressBookId(); AddressBook addressBook = addressBookService.getById(addressBookId); if(addressBook == null){ throw new CustomException("用户地址信息有误,无法完成订单"); } //生成订单号 long orderId = IdWorker.getId(); //原子操作,线程安全,多线程不会算错 AtomicInteger amount = new AtomicInteger(0); List<OrderDetail> orderDetails = list.stream().map((item) -> { OrderDetail orderDetail = new OrderDetail(); orderDetail.setOrderId(orderId); orderDetail.setNumber(item.getNumber()); orderDetail.setDishFlavor(item.getDishFlavor()); orderDetail.setDishId(item.getDishId()); orderDetail.setSetmealId(item.getSetmealId()); orderDetail.setName(item.getName()); orderDetail.setImage(item.getImage()); orderDetail.setAmount(item.getAmount()); amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue()); return orderDetail; }).collect(Collectors.toList()); //向订单表插入数据,一条数据 orders.setId(orderId); orders.setOrderTime(LocalDateTime.now()); orders.setCheckoutTime(LocalDateTime.now()); orders.setStatus(2); orders.setAmount(new BigDecimal(amount.get()));//总金额 orders.setUserId(currentId); orders.setNumber(String.valueOf(orderId)); orders.setUserName(user.getName()); orders.setConsignee(addressBook.getConsignee()); orders.setPhone(addressBook.getPhone()); orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) + (addressBook.getCityName() == null ? "" : addressBook.getCityName()) + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) + (addressBook.getDetail() == null ? "" : addressBook.getDetail())); this.save(orders); //向订单明细表插入数据,多条数据 orderDetailService.saveBatch(orderDetails); //清空购物车数据 shoppingCartService.remove(lqw); }
欢迎大家一起学习,有不足的地方还请指出。