Reputation: 31
Parent Class:
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
}
Child Class:
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
}
what i want to do is when deleting article for example with id = "1" it should delete all of its comments automatically ... so how to do that with annotations ??
in other words
for example when make delete request on postman on http://localhost:8080/articles/1
where 1 is article id to delete ... it should delete all of its comments aswell
Upvotes: 0
Views: 551
Reputation: 1604
Just Add OneToMany relation from Article
to the Comment
:
@OneToMany(mappedBy = "article", orphanRemoval = true)
private Set<Comment> comments = new HashSet<>();
Cascading REMOVE operations from the parent to the child require a relation from the parent to the child.
Update: Added orphanRemoval = true
Upvotes: 1
Reputation: 125
You shoud create other side of relationship is Article
which is:
@OneToMany(cascade=CascadeType.All)
@JoinColumn(name="article_id")
List<Comment> comments
So with this relationship if you delete one Article
all its comments will delete.
Upvotes: 1