Home Mapping one-to-many with no duplicates
Reply: 0

Mapping one-to-many with no duplicates

user1634 Published in June 23, 2018, 4:28 am

I'm attempting to do what I believe is a 'one-to-many' relationship in Jpa Spring JPA (Hibernate) where by I have three tables (Post, Tag, Post_tag).

One post may have many tags, and multiple posts may share the same tag as well as other tags. Where tags overlap, there should only be one instance of that tag in the tag table.

The structure goes a little like the following:


  • id
  • name


  • post_id
  • tag_id


  • id
  • tag

My understanding is that this is a 'many-to-one' relation from the Post's perspective, and a 'one-to-many' from the Tags perspective. Currently I've managed to make this work using a Many-To-One relationship, however this is producing many identical tags with different IDs and cluttering the database slowing it down and making me result in caching results in redis an attempt to speed up queries which is a temporary fix!

What I currently have is:

public class Post implements Serializable {


@ManyToOne(targetEntity = Tags.class, cascade = {CascadeType.ALL, CascadeType.MERGE})
@JoinTable(name = "post_tags",
            joinColumns = {@JoinColumn(name = "post_id")},
            inverseJoinColumns = {@JoinColumn(name = "tag_id", unique=true)})
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="post_tags")
    public Set<Tags> tags;

And the tags table:

@Column(name = "tag", unique = true)
private String tag;


You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307446 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO