休眠一对多关系:一旦父母被移除就无法移除孩子

我有一个课程评论一对多的关系。在课程表中有 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

}


潇潇雨雨
浏览 130回答 1
1回答

侃侃尔雅

您的评论从未真正属于该课程,因为您从未初始化关联的拥有部分: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){&nbsp; &nbsp; review.setCourse(this);&nbsp; &nbsp; reviews.add(review);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java