【问题标题】:JPA. Bidirectional association: ManyToOne. How to remove association when parent is removed?JPA。双向关联:ManyToOne。删除父级时如何删除关联?
【发布时间】:2021-05-28 19:00:56
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    相关资源
    最近更新 更多