本文主要是介绍@Builder和BeanUtils.copyProperties以及set方法造成数据库插入问题解决,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、引子
在写项目时,发现在插入数据库数据时,builder不能正常插入,而简单的set方法可以正常插入数据到数据库中。
二、项目背景
项目基于SpringBoot+Mybatis,用到的是Spring2.7
三、源码详细
OrderController
package com.sky.controller.user;import com.sky.dto.OrdersSubmitDTO;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController("userOrderController")
@RequestMapping("/user/order")
@Slf4j
@Api(tags = "C端-订单接口")
public class OrderController {@Autowiredprivate OrderService orderService;/*** 用户下单* @param ordersSubmitDTO* @return*/@PostMapping("/submit")@ApiOperation("用户下单")public Result<OrderSubmitVO> submit(@RequestBody OrdersSubmitDTO ordersSubmitDTO){log.info("用户下单:{}",ordersSubmitDTO);OrderSubmitVO orderSubmitVO = orderService.submitOrder(ordersSubmitDTO);return Result.success(orderSubmitVO);}
}
OrderService
package com.sky.service;import com.sky.dto.OrdersSubmitDTO;
import com.sky.vo.OrderSubmitVO;public interface OrderService {/*** 用户下单* @param ordersSubmitDTO* @return*/OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO);
}
OrderServiceImpl(用set)
package com.sky.service.impl;import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;@Service
public class OrderServiceImpl implements OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate AddressBookMapper addressBookMapper;@Autowiredprivate OrderDetailMapper orderDetailMapper;@Autowiredprivate ShoppingCartMapper shoppingCartMapper;/*** 用户下单** @param ordersSubmitDTO* @return*/public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {//1、处理各种业务异常(地址簿为空,购物车数据为空)AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());if (addressBook == null) {throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);}Long userId = BaseContext.getCurrentId();ShoppingCart shoppingCart = new ShoppingCart();shoppingCart.setUserId(userId);List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);if (shoppingCartList == null || shoppingCartList.size() == 0){throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);}//构造订单数据Orders orders = new Orders();BeanUtils.copyProperties(ordersSubmitDTO,orders);orders.setPhone(addressBook.getPhone());orders.setAddress(addressBook.getDetail());orders.setConsignee(addressBook.getConsignee());orders.setNumber(String.valueOf(System.currentTimeMillis()));orders.setUserId(userId);orders.setStatus(Orders.PENDING_PAYMENT);orders.setPayStatus(Orders.UN_PAID);orders.setOrderTime(LocalDateTime.now());//2、向订单插入一条数据orderMapper.insert(orders);//3、向订单明细表插入N条数据List<OrderDetail> orderDetails = new ArrayList<>();for (ShoppingCart cart : shoppingCartList) {OrderDetail orderDetail = new OrderDetail();BeanUtils.copyProperties(cart,orderDetail);orderDetail.setOrderId(orders.getId());orderDetails.add(orderDetail);}orderDetailMapper.insertBatch(orderDetails);//4、清空当前用户的购物车数据shoppingCartMapper.deleteByUserId(userId);//5、封装VO返回结果OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId()).orderNumber(orders.getNumber()).orderAmount(orders.getAmount()).orderTime(orders.getOrderTime()).build();return orderSubmitVO;}
}
OrderServiceImpl(用builder)
package com.sky.service.impl;import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;@Service
public class OrderServiceImpl implements OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate AddressBookMapper addressBookMapper;@Autowiredprivate OrderDetailMapper orderDetailMapper;@Autowiredprivate ShoppingCartMapper shoppingCartMapper;/*** 用户下单** @param ordersSubmitDTO* @return*/public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {//1、处理各种业务异常(地址簿为空,购物车数据为空)AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());if (addressBook == null) {throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);}Long userId = BaseContext.getCurrentId();ShoppingCart shoppingCart = new ShoppingCart();shoppingCart.setUserId(userId);List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);if (shoppingCartList == null || shoppingCartList.size() == 0){throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);}//构造订单数据Orders orders = new Orders();BeanUtils.copyProperties(ordersSubmitDTO,orders);orders =Orders.builder().phone(addressBook.getPhone()).address(addressBook.getDetail()).consignee(addressBook.getConsignee()).number(String.valueOf(System.currentTimeMillis())).userId(userId).status(Orders.PENDING_PAYMENT).payStatus(Orders.UN_PAID).orderTime(LocalDateTime.now()).build();//2、向订单插入一条数据orderMapper.insert(orders);//3、向订单明细表插入N条数据List<OrderDetail> orderDetails = new ArrayList<>();for (ShoppingCart cart : shoppingCartList) {OrderDetail orderDetail = new OrderDetail();BeanUtils.copyProperties(cart,orderDetail);orderDetail.setOrderId(orders.getId());orderDetails.add(orderDetail);}orderDetailMapper.insertBatch(orderDetails);//4、清空当前用户的购物车数据shoppingCartMapper.deleteByUserId(userId);//5、封装VO返回结果OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId()).orderNumber(orders.getNumber()).orderAmount(orders.getAmount()).orderTime(orders.getOrderTime()).build();return orderSubmitVO;}
}
OrderMapper
package com.sky.mapper;import com.sky.entity.Orders;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface OrderMapper {/*** 新增订单数据* @param orders*/void insert(Orders orders);
}
OrderMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace等于mapper接口类的全限定名,这样实现对应 -->
<mapper namespace="com.sky.mapper.OrderMapper"><insert id="insert" useGeneratedKeys="true" keyProperty="id">insert into orders(number, status, user_id, address_book_id, order_time, checkout_time, pay_method, pay_status, amount, remark,phone, address, consignee, estimated_delivery_time, delivery_status, pack_amount, tableware_number,tableware_status)values (#{number}, #{status}, #{userId}, #{addressBookId}, #{orderTime}, #{checkoutTime}, #{payMethod},#{payStatus}, #{amount}, #{remark}, #{phone}, #{address}, #{consignee},#{estimatedDeliveryTime}, #{deliveryStatus}, #{packAmount}, #{tablewareNumber}, #{tablewareStatus})</insert>
</mapper>
四、问题解决
因为builder方法相当于是重新创建一个地址,按照源码来看,先通过Order order = new Order()创建了一个地址A,在地址A里面通过BeanUtils.copyProperties来赋值,而后续的builder操作是重新创建了地址B,并把值封装在地址B里面,赋值完之后order对象的地址就变成了地址B,地址A的值就拿不到了。要想解决上面存在的问题,只需要把BeanUtils.copyProperties写在builder方法之后。即有
OrderServiceImpl
package com.sky.service.impl;import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.OrderService;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;@Service
public class OrderServiceImpl implements OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate AddressBookMapper addressBookMapper;@Autowiredprivate OrderDetailMapper orderDetailMapper;@Autowiredprivate ShoppingCartMapper shoppingCartMapper;/*** 用户下单** @param ordersSubmitDTO* @return*/public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {//1、处理各种业务异常(地址簿为空,购物车数据为空)AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());if (addressBook == null) {throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);}Long userId = BaseContext.getCurrentId();ShoppingCart shoppingCart = new ShoppingCart();shoppingCart.setUserId(userId);List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);if (shoppingCartList == null || shoppingCartList.size() == 0){throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);}//构造订单数据Orders orders = new Orders();orders =Orders.builder().phone(addressBook.getPhone()).address(addressBook.getDetail()).consignee(addressBook.getConsignee()).number(String.valueOf(System.currentTimeMillis())).userId(userId).status(Orders.PENDING_PAYMENT).payStatus(Orders.UN_PAID).orderTime(LocalDateTime.now()).build();BeanUtils.copyProperties(ordersSubmitDTO,orders);//2、向订单插入一条数据orderMapper.insert(orders);//3、向订单明细表插入N条数据List<OrderDetail> orderDetails = new ArrayList<>();for (ShoppingCart cart : shoppingCartList) {OrderDetail orderDetail = new OrderDetail();BeanUtils.copyProperties(cart,orderDetail);orderDetail.setOrderId(orders.getId());orderDetails.add(orderDetail);}orderDetailMapper.insertBatch(orderDetails);//4、清空当前用户的购物车数据shoppingCartMapper.deleteByUserId(userId);//5、封装VO返回结果OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId()).orderNumber(orders.getNumber()).orderAmount(orders.getAmount()).orderTime(orders.getOrderTime()).build();return orderSubmitVO;}
}
这篇关于@Builder和BeanUtils.copyProperties以及set方法造成数据库插入问题解决的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!