Welcome!
Here we will be covering how to map two models or two entities with many to many relations using spring boot hibernate:
For example, we have two tables, Posts, and Tags
we know there can be many to many relations between them like one post can have multiple tags and one tag can belong to multiple posts so to make MTM relation we have the code below:
Springboot will automatically make the 3rd table between them, there is no need to make the table hardcoded.
Post@Entity @Data public class Post { @Id @GeneratedValue private int id; private String pTitle; private String pDecription; private String pContent; private Date postedDate = new Date(); private Date lastUpdatedAt = new Date(); @ManyToMany @JoinTable( name = "post1", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "posts")) private Set<Tags> tags;
public Post(String pTitle, String pDecription, String pContent) { this.pTitle = pTitle; this.pDecription = pDecription; this.pContent = pContent; } }
|
Tags@Data @Entity public class Tags { @Id @GeneratedValue private long id; private String name; @ManyToMany(mappedBy = "tags") private Set<Post> posts;
}
|
Comments
Post a Comment
Let me know your doubts