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

JPA. Bidirectional association: ManyToOne. How to remove association when parent is removed?

我有两个实体: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;
}

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

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

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

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