考虑以下 JPA 实体:
@Entity @Table(name = "product") class Product { ... }
@Entity @Table(name = "stock") class Stock {
@JoinColumn(name = "product_id", updatable = false)
@ManyToOne(fetch = FetchType.LAZY)
private Product product;
@Column(name = "quantity")
private Long quantity;
}
@Entity @Table(name = "cart") class Cart {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "cart", orphanRemoval = true)
private List<CartItem> items = new ArrayList<>();
public void addItem(CartItem item) { items.add(item); }
public void removeItem(CartItem item) { items.remove(item); }
}
@Entity @Table(name = "cart_item") class CartItem {
@JoinColumn(name = "cart_id", updatable = false)
@ManyToOne(fetch = FetchType.LAZY)
private Cart cart;
@JoinColumn(name = "product_id", updatable = false)
@ManyToOne(fetch = FetchType.LAZY)
private Product product;
@Column(name = "quantity")
private Long quantity;
@JoinColumn(name = "stock_id", updatable = false)
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Stock stock;
public void setQuantity(Long quantity) {
final Long delta = this.quantity - Math.max(0L, quantity);
this.quantity += delta;
this.stock.setQuantity(this.stock.getQuantity() - delta);
if(quantity < 1) { cart.removeItem(this); }
}
}
注意从CartItem
到的关联Stock
。此关联已被注释,因此更改购物车项目数量会在另一个方向影响其可用库存,也就是说,如果购物车项目数量增加,产品的可用库存数量会减少,反之亦然。
这使我可以开火cartRepository.save(cart)
,保存所有购物车物品并同时更新其库存(由于Cascade.ALL
from Cart
to CartItem
)。只要购物车项目的数量非零,这就可以正常工作。
但是,当cartRepository.save(cart)
在调用 之后调用cart.removeItem(item)
时,级联也会尝试删除购物车项目的库存,这不是本意。应删除购物车项目,但应简单地更新其相关库存。有没有办法从 to 级联更新CartItem
,Stock
但级联删除CartItem
作为更新Stock
?