删除以多对一关系删除父项的子项

时间:2018-04-26 18:01:33

标签: java hibernate jpa

父类:

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上的邮递员发出删除请求时,其中1是要删除的文章ID ...它应该删除所有注释以及

2 个答案:

答案 0 :(得分:1)

只需将Article之间的OneToMany关系添加到Comment

@OneToMany(mappedBy = "article", orphanRemoval = true)
private Set<Comment> comments = new HashSet<>();

从父级到子级的级联REMOVE操作需要从父级到子级的关系。

更新:已添加orphanRemoval = true

答案 1 :(得分:1)

你要创建关系的另一面是code_challange,即:

Article

因此,如果您删除一个@OneToMany(cascade=CascadeType.All) @JoinColumn(name="article_id") List<Comment> comments,则此关系将删除所有注释。