![](/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.