我有一个问题,当我想从数据库中删除该产品,删除它,它应该从所有包含该产品的订单中删除。但当我试图这样做时,这是我得到的错误:
"error_message": "Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [fkbjvki7e3gm7vrphs73g4x7d2g]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
这是我的Order类:
@Entity
@Table(name="orders")
public class Order{
private @Id
@GeneratedValue
Long id;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL,orphanRemoval = true)
private List<ProductOrderDetails> orderedProducts = new ArrayList<>();
public void addProduct(Product product, int quantity) {
ProductOrderDetails orderedProduct = new ProductOrderDetails(this,product,quantity);
orderedProducts.add(orderedProduct);
product.getProductOrderDetails().add(orderedProduct);
totalOrderPrice+=product.getPrice()*quantity;
}
public void removeProduct(Product product,int quantity) {
ProductOrderDetails orderedProduct = new ProductOrderDetails( this, product,0);
product.getProductOrderDetails().remove(orderedProduct);
orderedProducts.remove(orderedProduct);
orderedProduct.setOrder(null);
orderedProduct.setProduct(null);
totalOrderPrice-=product.getPrice()*quantity;
}
}
这是我的产品类
@Entity
@Table
public class Product {
private @Id
@GeneratedValue
Long id;
private String name;
@OneToMany(mappedBy = "order", cascade = CascadeType.MERGE,orphanRemoval = true)
private List<ProductOrderDetails> productOrderDetails = new ArrayList<>();
}
产品订单ID
@Embeddable
public class ProdOrderId implements Serializable {
@Column(name = "order_id")
private Long orderId;
@Column(name = "product_id")
private Long productId;
}
产品和订单的多对多列
@Entity
@Table
public class ProductOrderDetails implements Serializable{
@EmbeddedId
@JsonIgnore
private ProdOrderId id;
@ManyToOne
@MapsId("orderId")
@JsonIgnore
Order order;
@ManyToOne
@MapsId("productId")
Product product;
private int quantity;
}
这是我的控制器方法
@DeleteMapping("/{id}")
ResponseEntity<?> deleteProduct(@PathVariable Long id)
{
repository.deleteById(id);
return ResponseEntity.noContent().build();
}
1条答案
按热度按时间kyvafyod1#
我不认为这是做什么你认为它在做什么:
如果您调试代码或检查
remove
的返回值,您会发现它返回的是false
,这意味着没有删除任何内容。您只是创建了一个新的
ProductOrderDetails
,然后试图将其从product.getProductOrderDetails()
中移除,但它并不存在于其中。您需要找到正确的元素以从该集合中移除。