1.代码的实现
package com.yzy.sell.Service.Impl; import com.yzy.sell.DTO.CateDTO; import com.yzy.sell.DTO.OrderDTO; import com.yzy.sell.Entity.OrderDetail; import com.yzy.sell.Entity.OrderMaster; import com.yzy.sell.Entity.ProductInfo; import com.yzy.sell.Enums.OrderStatusEnum; import com.yzy.sell.Enums.PayStatusEnum; import com.yzy.sell.Enums.ResultEnum; import com.yzy.sell.Repository.OrderDetailRepository; import com.yzy.sell.Repository.OrderMasterRepository; import com.yzy.sell.Repository.ProductInfoRepository; import com.yzy.sell.Service.OrderService; import com.yzy.sell.Service.ProductService; import com.yzy.sell.exception.SellException; import com.yzy.sell.utils.KeyUtil; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import java.util.stream.Collectors; @Service public class OrderServiceImpl implements OrderService { @Autowired private ProductInfoRepository productInfoRepository; @Autowired private ProductService productService; @Autowired private OrderDetailRepository orderDetailRepository; @Autowired private OrderMasterRepository orderMasterRepository; @Override @Transactional //添加此标签后,发生异常数据库会回滚操作 public OrderDTO create(OrderDTO orderDTO) { String orderId= KeyUtil.genUniqueKey(); List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList(); BigDecimal orderAmount=new BigDecimal(BigInteger.ZERO); //1.获取商品价格、名字 for(OrderDetail orderDetail:orderDetailList){ ProductInfo productInfo = productInfoRepository.findById(orderDetail.getProductId()).get(); if(productInfo==null){ new SellException(ResultEnum.PRODUCT_NO_EXIST); } //2.计算订单总价 orderAmount=productInfo.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity())) .add(orderAmount); //3.1写入订单详情(orderDetail)数据库 orderDetail.setDetailId(KeyUtil.genUniqueKey()); orderDetail.setOrderId(orderId); BeanUtils.copyProperties(productInfo,orderDetail); orderDetailRepository.save(orderDetail); } //3.2写入订单(orderMaster)数据库 OrderMaster orderMaster=new OrderMaster(); orderDTO.setOrderId(orderId); BeanUtils.copyProperties(orderDTO,orderMaster); orderMaster.setOrderAmount(orderAmount); orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode()); orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode()); orderMasterRepository.save(orderMaster); //4.减库存 List<CateDTO> cateDTOList=orderDetailList.stream().map(e-> new CateDTO(e.getProductId(),e.getProductQuantity())) .collect(Collectors.toList()); productService.decreaseStock(cateDTOList); return orderDTO; }
2.关于@Transactional的使用
3.关于lambda表达式的使用
@Transactional