我有一个课程评论一对多的关系。在课程表中有 id 和 title 列。在 Review 表中有 id、comment 和 course_id,其中“course_id”作为 FK 指向 Course id。我想实现这样的场景,一旦课程被删除,相关的评论就会被自动删除。我有以下代码:
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "title")
private String title;
@OneToMany(mappedBy = "course", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Review> reviews;
public void addReview(Review review){
if(reviews==null) reviews = new ArrayList<>();
reviews.add(review);
}
//other codes below omitted
}
@Entity
@Table(name = "review")
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "comment")
private String comment;
@ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "course_id")
private Course course;
//other codes omitted
}
侃侃尔雅
相关分类