我有一个课程评论一对多的关系。在课程表中有 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}
1 回答
侃侃尔雅
TA贡献1801条经验 获得超16个赞
您的评论从未真正属于该课程,因为您从未初始化关联的拥有部分:Review.course。将您的addReview()方法更改为
@OneToMany(mappedBy = "course", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private List<Review> reviews = new ArrayList<>();
public void addReview(Review review){
review.setCourse(this);
reviews.add(review);
}
添加回答
举报
0/150
提交
取消