Search code examples
spring-bootspring-data-jpaforeign-keyssql-delete

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


I have two entities: Product and Category

  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;
}

I want to keep my childs (products) in db (with the value of category equal to null) after removing the parent (category). Currently, when I try to delete a category, I get this error:

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

Solution

  • Before deleting the category you need to update the association. For example:

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