Reputation: 2918
I am trying to have a many-to-many bidirectional relationship for 2 entities (News and Tag).
But when I try to saveOrUpdate the News (which has Set), somehow it always saves a new set of Tag even id is already populated in the Tag
Is it something wrong with my annotation?
News.java
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "NEWS_ID")
public Long getId() {
return id;
}
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@Cascade( org.hibernate.annotations.CascadeType.SAVE_UPDATE )
@JoinTable(name = "NEWS_TAGS", joinColumns = @JoinColumn(name = "NEWS_ID"), inverseJoinColumns = @JoinColumn(name = "TAG_ID"))
public Set<Tag> getTags() {
return tags;
}
Tag.java
@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "TAG_ID")
public Long getId() {
return id;
}
private Collection<News> news;
@JsonIgnore
@ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "tags")
public Collection<News> getNews() {
return news;
}
NewsDAO
public void save(News news){
this.hibernateSessionFactory.getCurrentSession().saveOrUpdate(news);
}
What I want to do is when, I save "News", the related Set will be ignored if Tag exist, and will insert new if Tag isn't, is this possible?
Please advise
Upvotes: 1
Views: 1360
Reputation: 1239
The problem is that your object (Tag) is not "connected". By that I mean hibernate is not aware of your object and, when you try to save News, hibernate will see your Tags as new Objects always. Try get the Tag object from db before save or update and use this object.
Upvotes: 2