Search code examples
jpamany-to-manycascade

JPA: Should cascading from SQL script be reflected in entity?


I have two entities: course and category that are associated by the @ManyToMany annotation.

@Entity
@Table(name = "categories")
public class Category {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int categoryId;
    private String name;

    @ManyToMany(cascade = CascadeType.PERSIST)
    @JoinTable(
            name="course_category",
            joinColumns = @JoinColumn(name = "category_id"),
            inverseJoinColumns = @JoinColumn(name = "course_id")
    )
    private Set<Course> courses;
}
@Entity
@Table(name = "courses")
public class Course {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int courseId;
    @NotBlank(message = "Add the course's title!")
    private String title;
    private String description;

    @ManyToMany(mappedBy = "courses")
    private Set<Category> categories;
}

My goal is that after deleting a category, the courses related to that category will not be deleted, only the association must be broken So I included ON DELETE CASCADE when creating the join table.

  CREATE TABLE course_category (
    category_id INT NOT NULL,
    course_id INT NOT NULL,
    FOREIGN KEY (category_id)
        REFERENCES categories(category_id)
        ON DELETE CASCADE,
    FOREIGN KEY (course_id)
        REFERENCES courses(course_id)
        ON DELETE CASCADE
    PRIMARY KEY (category_id, course_id)
)

If I am not wrong it should do my goal. But now my question is: Should I reflect ON DELETE CASCADE in my entity? If so, how can I do it? By adding CascadeType.REMOVE?


Solution

  • You should avoid on delete cascade with JPA because that way the database will delete rows that may be still present in the JPA persistence context.

    Instead use CascadeType.REMOVE and/or orphanRemoval=true to cascade JPA remove operations.