![](/img/trans.png)
[英]Springboot 2 CrudRepository.save always throws ConstraintViolationException
[英]Remove row from table throws ConstraintViolationException
當我想從數據庫中刪除產品時遇到問題,刪除它,它應該從包含該產品的所有訂單中刪除。 但是當我嘗試這樣做時,這是我得到的錯誤:
"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"
這是我的訂單 class:
@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;
}
}
這是我的產品 class
@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;
}
這是我的 controller 方法
@DeleteMapping("/{id}")
ResponseEntity<?> deleteProduct(@PathVariable Long id)
{
repository.deleteById(id);
return ResponseEntity.noContent().build();
}
我不認為這是在做你認為它在做的事情:
ProductOrderDetails orderedProduct = new ProductOrderDetails( this, product,0);
product.getProductOrderDetails().remove(orderedProduct);
如果您調試代碼或檢查remove
的返回值,您會發現它返回false
,這意味着沒有任何內容被刪除。
您只是在創建一個新的ProductOrderDetails
,然后嘗試將其從product.getProductOrderDetails()
中刪除,但其中不存在。 您需要找到要從該集合中刪除的正確元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.