我正在尝试为 2 个实体(新闻和标签)建立多对多双向关系。
但是当我尝试保存或更新新闻(已设置)时,它总是以某种方式保存一组新的标签,即使标签中已经填充了 id
我的注释有问题吗?
新闻.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;
}
标签.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;
}
新闻DAO
public void save(News news){
this.hibernateSessionFactory.getCurrentSession().saveOrUpdate(news);
}
我想要做的是,当我保存“新闻”时,如果标签存在,相关的集合将被忽略,如果标签不存在,将插入新的,这可能吗?
请指教