首页 > 数据库 >添加数据库事务

添加数据库事务

时间:2022-12-18 22:34:05浏览次数:34  
标签:事务 orderItem cartVOListTemp int 数据库 cartVOList orderItemsList 添加 cartVO

//数据库事务 @Transactional(rollbackFor = Exception.class)
具体实例
`@Transactional(rollbackFor = Exception.class)
@Override
public String create(CreateOrderReq createOrderReq){
//拿到用户ID
Integer userId = UserFilter.currentUser.getId();
//从购物车查找已勾选的商品
List cartVOList = cartService.list(userId);
ArrayList cartVOListTemp = new ArrayList<>();
for (int i = 0; i < cartVOList.size(); i++) {
CartVO cartVO = cartVOList.get(i);
if (cartVO.getSelected().equals(Constant.Cart.CHECKED)){
cartVOListTemp.add(cartVO);
}
}
cartVOList = cartVOListTemp;
//如果购物车已勾选的为空,就报错
if(CollectionUtils.isEmpty(cartVOList)){
throw new ImoocMallException(ImoocMallExceptionEnum.CART_EMPTY);
}
//判断商品是否存在,上下架状态,库存
validSaleStatusAndStock(cartVOList);

    //把购物车对象转化为订单item对象
    List<OrderItem> orderItemsList = cartVOListToOrderItemList(cartVOList);
    //扣库存
    for (int i = 0; i < orderItemsList.size(); i++) {
        OrderItem orderItem =  orderItemsList.get(i);
        Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
        int stock = product.getStock() - orderItem.getQuantity();
        if (stock<0){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_ENOUGH);
        }
        product.setStock(stock);
        productMapper.updateByPrimaryKeySelective(product);
    }

    //把购物车中的已勾选的商品删除
    cleanCart(cartVOList);
    //生成订单
    Order order = new Order();
    //生成订单号,有独立的规则
    String orderNo = OrderCodeFactory.getOrderCode(Long.valueOf(userId));
    order.setOrderNo(orderNo);
    order.setUserId(userId);
    order.setTotalPrice(totalPrice(orderItemsList));
    order.setReceiverName(createOrderReq.getReceiverName());
    order.setReceiverMobile(createOrderReq.getReceiverMobile());
    order.setReceiverAddress(createOrderReq.getReceiverAddress());
    order.setOrderStatus(Constant.OrderStatusEnum.NOT_PAID.getCode());
    order.setPostage(0);
    order.setPaymentType(1);
    //插入到order表
    orderMapper.insertSelective(order);


    //循环保存每个商品的order_item表
    for (int i = 0; i < orderItemsList.size(); i++) {
        OrderItem orderItem = orderItemsList.get(i);
        orderItem.setOrderNo(order.getOrderNo());
        orderItemMapper.insertSelective(orderItem);

    }

    //把结果返回

    return orderNo;
}`

标签:事务,orderItem,cartVOListTemp,int,数据库,cartVOList,orderItemsList,添加,cartVO
From: https://www.cnblogs.com/heiyu-sec/p/16991095.html

相关文章