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

Mapping one-to-many with no duplicates

user6495
1#
user6495 Published in September 20, 2018, 12:44 pm

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:

Post:

  • id
  • name

Post_tag:

  • post_id
  • tag_id

Tag:

  • 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:

@Table(name="Post")
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;

Thanks!

share|improve this question
  • This is a many to many mapping – Mark D Feb 12 at 21:17
  • How can a Set field be a @ManyToOne??? It can't. – user8558216 Feb 13 at 7:25

2 Answers 2

active oldest votes
up vote 1 down vote
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO