无法删除或更新父行:外键约束失败(
gopick.orders_paid_items,约束FKeeefhbl6j5xhs7nnt5mn530f8外键(paid_items_product_id,paid_items_user_id)引用cart(product_id,user_id))
以下购物车实体
@Entity
@ToString
@EqualsAndHashCode
@IdClass(CartIdPk.class)
public class Cart implements Serializable {
@Column(unique = true)
private Long id = Long.parseLong(String.format("%06d", new Random().nextInt(999999)));
@JsonIgnore
@Id
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private User user;
private CartStatus cartStatus = CartStatus.IN_CART;
@Id
private int productId;
private int quantity = 0;
@Column(length = 10, nullable = true)
private String discount;
@Column(length = 30, nullable = true)
private String paymentRef;
@JsonIgnore
@Column(insertable = false, updatable = true)
@UpdateTimestamp
private Timestamp lastModified;
@CreationTimestamp
private Timestamp dateCreated;
}Id类对象CartIdPk
@NoArgsConstructor
@AllArgsConstructor
@lombok.Data
public class CartIdPk implements Serializable {
private Long user;
private int productId;
}以下订单实体
@lombok.Data
@Entity
public class Orders implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@OneToMany(fetch = FetchType.LAZY)
private Collection<Cart> paidItems;
@JsonIgnore
@Column(insertable = false, updatable = true)
@UpdateTimestamp
private Timestamp lastModified;
@CreationTimestamp
private Timestamp dateCreated;
}当我尝试从Cart实体表中删除时,如果生成的productId中不存在orders_paid_items,它就会完美地工作,但是如果它存在,则会抛出一个错误,如前所述。
使用默认的CrudRepository删除方法从cart表中删除项,如下所示
cartDataService.remove(cartDataService.find(cartId));发布于 2020-05-08 08:53:32
在java中使用JPA和ORMs的经验法则是记住,您有一个对象模型和一个关系数据库模型,并且您必须对这两个模型进行更改。
所以在订单和手推车之间有1比多。
因此,为了便于讨论,您尝试删除当前按顺序排列的购物车。当保存发生时,您将得到一个完整性冲突,因为您试图删除的购物车仍然被一个订单引用。
您需要做的是删除之前从卡中删除订单,因为您在订单中引用的是购物车。
始终尝试在“对象”级别和数据库级别进行更改。
https://stackoverflow.com/questions/61675160
复制相似问题