Need solution for following scenario in Hibernate many to many mapping












0















Consider the tables where posts and tags exhibit a many-to-many relationship between each other.



The many-to-many relationship is implemented using a third table called post_tags which contains the details of posts and their associated tags.



Post Model

@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 100)
@Column(unique = true)
private String title;

@NotNull
@Size(max = 250)
private String description;

@NotNull
@Lob
private String content;

@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "posted_at")
private Date postedAt = new Date();

@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_updated_at")
private Date lastUpdatedAt = new Date();


@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "post_tags",
joinColumns = { @JoinColumn(name = "post_id") },
inverseJoinColumns = { @JoinColumn(name = "tag_id") })
private Set<Tag> tags = new HashSet<>();


public Post() {

}

public Post(String title, String description, String content) {
this.title = title;
this.description = description;
this.content = content;
}

// Getters and Setters (Omitted for brevity)
}




TAG Model

@Entity
@Table(name = "tags")
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 100)
@NaturalId
private String name;

@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "tags")
private Set<Post> posts = new HashSet<>();

public Tag() {

}

public Tag(String name) {
this.name = name;
}

// Getters and Setters (Omitted for brevity)
}


Problem is



I tried to use an existing tags. and insert happened only on posts & posts_tags table.



Initially i'm Get tag(s) with tagName(s). Once you have the Tag object, you can set it in the Post object and save it.



Like this



 Post post = new Post("Hibernate Many to Many Example with Spring Boot",
"Learn how to map a many to many relationship using hibernate",
"Entire Post content with Sample code");

// Create two tags
Tag tag1 = tagService.getTag("Spring Boot");


// Add tag references in the post
post.getTags().add(tag1);

postRepository.save(post);


If I do like that, entry is not available in post_tags table.



Tag Repository and Tag Service:



@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {

@Query("select p from Tag p where p.name = :name")
Tag findByName(@Param("name") String name);
}

@Override
public Tag findByName(String name) {
return repository.findByName(name);
}









share|improve this question

























  • Can you share the code of tagService.getTag

    – codeLover
    Nov 17 '18 at 3:15











  • Here I updated the tagService,getTag() for your reference

    – Seenivasan Sankaran
    Nov 17 '18 at 13:48











  • Still unable to find getTag method...

    – codeLover
    Nov 19 '18 at 3:53
















0















Consider the tables where posts and tags exhibit a many-to-many relationship between each other.



The many-to-many relationship is implemented using a third table called post_tags which contains the details of posts and their associated tags.



Post Model

@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 100)
@Column(unique = true)
private String title;

@NotNull
@Size(max = 250)
private String description;

@NotNull
@Lob
private String content;

@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "posted_at")
private Date postedAt = new Date();

@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_updated_at")
private Date lastUpdatedAt = new Date();


@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "post_tags",
joinColumns = { @JoinColumn(name = "post_id") },
inverseJoinColumns = { @JoinColumn(name = "tag_id") })
private Set<Tag> tags = new HashSet<>();


public Post() {

}

public Post(String title, String description, String content) {
this.title = title;
this.description = description;
this.content = content;
}

// Getters and Setters (Omitted for brevity)
}




TAG Model

@Entity
@Table(name = "tags")
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 100)
@NaturalId
private String name;

@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "tags")
private Set<Post> posts = new HashSet<>();

public Tag() {

}

public Tag(String name) {
this.name = name;
}

// Getters and Setters (Omitted for brevity)
}


Problem is



I tried to use an existing tags. and insert happened only on posts & posts_tags table.



Initially i'm Get tag(s) with tagName(s). Once you have the Tag object, you can set it in the Post object and save it.



Like this



 Post post = new Post("Hibernate Many to Many Example with Spring Boot",
"Learn how to map a many to many relationship using hibernate",
"Entire Post content with Sample code");

// Create two tags
Tag tag1 = tagService.getTag("Spring Boot");


// Add tag references in the post
post.getTags().add(tag1);

postRepository.save(post);


If I do like that, entry is not available in post_tags table.



Tag Repository and Tag Service:



@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {

@Query("select p from Tag p where p.name = :name")
Tag findByName(@Param("name") String name);
}

@Override
public Tag findByName(String name) {
return repository.findByName(name);
}









share|improve this question

























  • Can you share the code of tagService.getTag

    – codeLover
    Nov 17 '18 at 3:15











  • Here I updated the tagService,getTag() for your reference

    – Seenivasan Sankaran
    Nov 17 '18 at 13:48











  • Still unable to find getTag method...

    – codeLover
    Nov 19 '18 at 3:53














0












0








0








Consider the tables where posts and tags exhibit a many-to-many relationship between each other.



The many-to-many relationship is implemented using a third table called post_tags which contains the details of posts and their associated tags.



Post Model

@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 100)
@Column(unique = true)
private String title;

@NotNull
@Size(max = 250)
private String description;

@NotNull
@Lob
private String content;

@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "posted_at")
private Date postedAt = new Date();

@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_updated_at")
private Date lastUpdatedAt = new Date();


@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "post_tags",
joinColumns = { @JoinColumn(name = "post_id") },
inverseJoinColumns = { @JoinColumn(name = "tag_id") })
private Set<Tag> tags = new HashSet<>();


public Post() {

}

public Post(String title, String description, String content) {
this.title = title;
this.description = description;
this.content = content;
}

// Getters and Setters (Omitted for brevity)
}




TAG Model

@Entity
@Table(name = "tags")
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 100)
@NaturalId
private String name;

@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "tags")
private Set<Post> posts = new HashSet<>();

public Tag() {

}

public Tag(String name) {
this.name = name;
}

// Getters and Setters (Omitted for brevity)
}


Problem is



I tried to use an existing tags. and insert happened only on posts & posts_tags table.



Initially i'm Get tag(s) with tagName(s). Once you have the Tag object, you can set it in the Post object and save it.



Like this



 Post post = new Post("Hibernate Many to Many Example with Spring Boot",
"Learn how to map a many to many relationship using hibernate",
"Entire Post content with Sample code");

// Create two tags
Tag tag1 = tagService.getTag("Spring Boot");


// Add tag references in the post
post.getTags().add(tag1);

postRepository.save(post);


If I do like that, entry is not available in post_tags table.



Tag Repository and Tag Service:



@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {

@Query("select p from Tag p where p.name = :name")
Tag findByName(@Param("name") String name);
}

@Override
public Tag findByName(String name) {
return repository.findByName(name);
}









share|improve this question
















Consider the tables where posts and tags exhibit a many-to-many relationship between each other.



The many-to-many relationship is implemented using a third table called post_tags which contains the details of posts and their associated tags.



Post Model

@Entity
@Table(name = "posts")
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 100)
@Column(unique = true)
private String title;

@NotNull
@Size(max = 250)
private String description;

@NotNull
@Lob
private String content;

@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "posted_at")
private Date postedAt = new Date();

@NotNull
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_updated_at")
private Date lastUpdatedAt = new Date();


@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "post_tags",
joinColumns = { @JoinColumn(name = "post_id") },
inverseJoinColumns = { @JoinColumn(name = "tag_id") })
private Set<Tag> tags = new HashSet<>();


public Post() {

}

public Post(String title, String description, String content) {
this.title = title;
this.description = description;
this.content = content;
}

// Getters and Setters (Omitted for brevity)
}




TAG Model

@Entity
@Table(name = "tags")
public class Tag {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@NotNull
@Size(max = 100)
@NaturalId
private String name;

@ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
},
mappedBy = "tags")
private Set<Post> posts = new HashSet<>();

public Tag() {

}

public Tag(String name) {
this.name = name;
}

// Getters and Setters (Omitted for brevity)
}


Problem is



I tried to use an existing tags. and insert happened only on posts & posts_tags table.



Initially i'm Get tag(s) with tagName(s). Once you have the Tag object, you can set it in the Post object and save it.



Like this



 Post post = new Post("Hibernate Many to Many Example with Spring Boot",
"Learn how to map a many to many relationship using hibernate",
"Entire Post content with Sample code");

// Create two tags
Tag tag1 = tagService.getTag("Spring Boot");


// Add tag references in the post
post.getTags().add(tag1);

postRepository.save(post);


If I do like that, entry is not available in post_tags table.



Tag Repository and Tag Service:



@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {

@Query("select p from Tag p where p.name = :name")
Tag findByName(@Param("name") String name);
}

@Override
public Tag findByName(String name) {
return repository.findByName(name);
}






spring hibernate many-to-many






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 '18 at 13:47







Seenivasan Sankaran

















asked Nov 16 '18 at 12:03









Seenivasan SankaranSeenivasan Sankaran

12




12













  • Can you share the code of tagService.getTag

    – codeLover
    Nov 17 '18 at 3:15











  • Here I updated the tagService,getTag() for your reference

    – Seenivasan Sankaran
    Nov 17 '18 at 13:48











  • Still unable to find getTag method...

    – codeLover
    Nov 19 '18 at 3:53



















  • Can you share the code of tagService.getTag

    – codeLover
    Nov 17 '18 at 3:15











  • Here I updated the tagService,getTag() for your reference

    – Seenivasan Sankaran
    Nov 17 '18 at 13:48











  • Still unable to find getTag method...

    – codeLover
    Nov 19 '18 at 3:53

















Can you share the code of tagService.getTag

– codeLover
Nov 17 '18 at 3:15





Can you share the code of tagService.getTag

– codeLover
Nov 17 '18 at 3:15













Here I updated the tagService,getTag() for your reference

– Seenivasan Sankaran
Nov 17 '18 at 13:48





Here I updated the tagService,getTag() for your reference

– Seenivasan Sankaran
Nov 17 '18 at 13:48













Still unable to find getTag method...

– codeLover
Nov 19 '18 at 3:53





Still unable to find getTag method...

– codeLover
Nov 19 '18 at 3:53












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337541%2fneed-solution-for-following-scenario-in-hibernate-many-to-many-mapping%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53337541%2fneed-solution-for-following-scenario-in-hibernate-many-to-many-mapping%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Xamarin.iOS Cant Deploy on Iphone

Glorious Revolution

Dulmage-Mendelsohn matrix decomposition in Python