@Service
public class PurchaseServiceImpl implements PurchaseService {
@Autowired
private PurchaseRepository purchaseRepository;
@Autowired
private CustomerService customerService;
@Autowired
private CartService cartService;
@Override
public void placeOrder(PlaceOrderRequest placeOrderRequest) {
Customer customer = this.customerService.getCustomer(placeOrderRequest.getCustomerId());
Cart cart = customer.getCart();
if (cart == null || cart.getProducts().isEmpty()) {
throw new RuntimeException("Cart is empty. Cannot be ordered.");
}
Purchase purchase = new Purchase();
purchase.setCarts(List.of(cart));
purchase.setTotalPrice(cart.getTotalPrice());
purchase.setCustomer(customer);
customer.getPurchases().add(purchase);
this.purchaseRepository.save(purchase);
this.customerService.addCustomer(customer);
this.cartService.emptyCart(cart.getId());
}
如您所见,我创建了一个新的 List 对象,并为 buy.setCarts 添加了当前的购物车实例。即使当我调用 cartService.emptyCart 时也清空了 buy.getCarts 。你能解释一下吗?
在您的代码中,当您使用
purchase.setCarts(List.of(cart))
设置购买购物车时,您实际上传递了对从客户购物车检索到的同一 cart
对象的引用。因此,当您稍后调用 this.cartService.emptyCart(cart.getId())
时,它会清空购买引用的同一购物车对象。
在Java中,对象是通过引用传递的,这意味着当您将对象传递给方法时,您传递的是对内存中实际对象的引用,而不是它的副本。因此,在方法内对该对象所做的任何更改也会影响方法外的原始对象。
为了避免这种行为,您应该在将购物车对象设置为购买之前创建购物车对象的副本,以便对原始购物车对象所做的更改不会影响与购买关联的购物车对象。您可以通过创建购物车对象的新实例并复制相关属性来完成此操作。