父类:
public class Article implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Email
@NotNull
@Column(name = "email")
String email;
@Column(name = "title")
String title;
@Column(name = "published")
Boolean published;
@OneToMany(mappedBy = "article", cascade = {CascadeType.REMOVE}, orphanRemoval = true)
private Set<Comment> comments = new HashSet<>();
// setters and getters
}
子类:
public class Comment implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
@Email
@NotNull
@Column(name = "email")
String email;
@JsonIgnore
@ManyToOne
@JoinColumn(name = "article_id", referencedColumnName = "id")
Article article;
// setters and getters
}
我想要做的是,当删除文章时,例如 id =“1”,它应该自动删除其所有评论......那么如何使用注释来做到这一点?
换句话说
例如,当在 http://localhost:8080/articles/1
上对 postman 发出删除请求时,其中 1 是要删除的文章 ID ...它也应该删除其所有评论
最佳答案
只需将 Article
中的 OneToMany 关系添加到 Comment
即可:
@OneToMany(mappedBy = "article", orphanRemoval = true)
private Set<Comment> comments = new HashSet<>();
从父级到子级的级联 REMOVE 操作需要父级到子级的关系。
更新:添加了orphanRemoval = true
关于java - 删除多对一关系中删除父级的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50049370/