So I have a shopping cart API, I have a Cart with OneToMany CartItem, and CartItem with ManyToOne Product.
In my service, I have this code for adding the item:
Cart cart = cartRepository.findById(cartId).orElseThrow(CartNotFoundException::new);
Product product = productRepository.findById(productId).orElseThrow(ProductNotFoundException::new);
cart.addItem(product);
cartRepository.save(cart);
addItem:
public void addItem(Product product) {
CartItem cartItem = getItem(product.getId());
if (cartItem != null) {
cartItem.setQuantity(cartItem.getQuantity() + 1);
} else {
cartItem = new CartItem();
cartItem.setCart(this);
cartItem.setProduct(product);
cartItem.setQuantity(1);
items.add(cartItem);
}
}
All of these result in a total of 4 (when I add quantity) database queries, is this something concerning or do I need to optimize?