JPA:来自 SQL 脚本的级联应该反映在实体中吗?
JPA: Should cascading from SQL script be reflected in entity?
我有两个实体:course
和 category
,它们由 @ManyToMany
注释关联。
@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;
}
我的目标是删除一个类别后,与该类别相关的课程不会被删除,只有关联必须被打破所以我在创建连接时包含了ON DELETE CASCADE
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)
)
如果我没记错的话,它应该可以实现我的目标。
但现在我的问题是:我应该在我的实体中反映 ON DELETE CASCADE
吗?如果是这样,我该怎么做?通过添加 CascadeType.REMOVE?
您应该避免 on delete cascade
使用 JPA,因为那样的话数据库将删除可能仍存在于 JPA 持久性上下文中的行。
而是使用 CascadeType.REMOVE
and/or orphanRemoval=true
级联 JPA 删除操作。
我有两个实体:course
和 category
,它们由 @ManyToMany
注释关联。
@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;
}
我的目标是删除一个类别后,与该类别相关的课程不会被删除,只有关联必须被打破所以我在创建连接时包含了ON DELETE CASCADE
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)
)
如果我没记错的话,它应该可以实现我的目标。
但现在我的问题是:我应该在我的实体中反映 ON DELETE CASCADE
吗?如果是这样,我该怎么做?通过添加 CascadeType.REMOVE?
您应该避免 on delete cascade
使用 JPA,因为那样的话数据库将删除可能仍存在于 JPA 持久性上下文中的行。
而是使用 CascadeType.REMOVE
and/or orphanRemoval=true
级联 JPA 删除操作。