I have the model below : an article can have some tags and a tag can be on some articles. So it is a many-to-many relationship with 3 tables :
- ARTICLE
- ARTICLE_TAG
- TAG
When I delete a tag, I want to delete :
- the tag in TAG
- all relations between the tag and the articles tagged in ARTICLE_TAG
But I don't want to delete the articles in ARTICLE of course.
How can I do that ?
I try this, but it doesn't work :
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
for (Article article : tagToDelete.getArticles()) {
article.getTags().remove(tagToDelete);
}
session.delete(tagToDelete);
Thanks !
@Entity
@Table(name="ARTICLE")
public class Article extends AbstractAuditedEntity {
@Id
@Column(name="ID", nullable=false)
private Long id;
@ManyToMany
@JoinTable(name="ARTICLE_TAG", joinColumns=@JoinColumn(name = "ARTICLE_ID"), inverseJoinColumns=@JoinColumn(name = "TAG_ID"))
private Set<Tag> tags = new HashSet<>();
public Article() {}
/** Getters & Setters */
}
@Entity
@Table(name="TAG")
public class Tag {
@Id
@Column(name="ID", nullable=false)
private Long id;
@ManyToMany(mappedBy="tags")
private Set<Article> articles = new HashSet<>();
public Tag() {}
/** Getters & Setters */
}