JPA。双向关联:ManyToOne。删除父级时如何删除关联?

时间:2021-05-28 19:00:56

标签: spring-boot spring-data-jpa foreign-keys sql-delete

我有两个实体:ProductCategory

  public class Category {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int id;

    @OneToMany(cascade =  CascadeType.PERSIST, mappedBy = "category")
    private Set<Product> products;
}

public class Product {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int id;

    @ManyToOne
    @JoinColumn(name = "categories_id")
    private Category category;
}

我想在删除父级(类别)后将我的孩子(产品)保留在 db 中(category 的值等于 null)。 目前,当我尝试删除类别时,出现此错误:

org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referential integrity constraint violation: "CONSTRAINT_F2: PUBLIC.PRODUCTS FOREIGN KEY(CATEGORIES_ID) REFERENCES PUBLIC.CATEGORIES(ID)

1 个答案:

答案 0 :(得分:1)

在删除类别之前,您需要更新关联。 例如:

Category category = ...
for (Product p : category.getProducts()) {
   p.setCategory(null);
}
category.getProducts().clear();
entityManager.remove(category);