New to this forum + hibernate!
I have two model classes -- Article and Tag -- annotated as follows:
Code:
@Entity
@Table(name="articles")
public class Article {
@Id
@GeneratedValue
private int id;
@Column(length=255, nullable=false)
private String title;
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name = "articles_tags",
joinColumns = @JoinColumn(name = "article_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "tag_id", referencedColumnName = "id"))
@OrderBy("name ASC")
private List<Tag> tags = new ArrayList<>();
...
}
@Entity
@Table(name = "tags")
public class Tag {
@javax.persistence.Id
@GeneratedValue
private int Id;
@Column(length = 30, nullable = false, unique = true)
private String name;
@ManyToMany(mappedBy = "tags")
private Collection<Article> articles = new ArrayList<>();
..
}
I have a form to prepare article with relevant tags for the topic. On submission of the article, it can populate all necessary tables,
viz. articles, tags and articles_tags, with no problem as long as the input tags are new. If the included tag is already in the database, however, it does not
work.
So, basically, I have to ensure is that if tag is new insert into List<Tag> list, and insert into the table, otherwise simply use the tag object
from the database in the List. I am pretty new to hibernate, could somebody in the forum provide some pointers on this?
Thanks,