Am getting an error while updating the existing entity with below approach using PostRepository save method.
Here are my objects,
@Entity
public class Post {
@Id
private String postId;
private String postName;
@OneToMany(mappedBy = "Post", cascade = CascadeType.ALL)
private Collection<PostTag> postTags = new HashSet<PostTag>();
}
@Entity
public class Tag {
@Id
private String tagId;
private String tagName;
@OneToMany(mappedBy = "tag", cascade = CascadeType.ALL)
@JsonIgnore
private Collection<PostTag> postTags = new HashSet<PostTag>();
}
@Entity
public class PostTag {
@EmbeddedId
private PostTagId postTagId = new PostTagId();
@ManyToOne
@MapsId("postId")
@JoinColumn(name = "post_Id")
@JsonIgnore
private Post post;
@ManyToOne
@MapsId("tagId")
@JoinColumn(name = "tag_Id")
private Tag tag;
//extra columns ommited
}
@Embeddable
public class PostTagId implements Serializable {
private String postId;
private String tagId;
//equals & hashcode ommited
}
I try to save the post as in the form of below POST json,
{
"postId": "post-001",
"postName": "post-001",
"postTags": [
{
"tag": {
"tagId": "tag-001",
"tagName": "tag-001"
}
}
]
}
Service implementation looks as below,
public Post save(Post post){
Post newPost = new Post();
newPost.setPostName(Post.getPostName());
newPost.setPostId(Post.getPostId());
for (PostTag posttag : post.getPostTags()) {
PostTag newPostTag = new PostTag();
Tag dbTag = tagRepo.getById(posttag.getTag().getTagId());
if(dbTag == null){
Tag newtag = new Tag();
newtag.setTagId(posttag.getTag().getTagId());
newtag.setTagName(posttag.getTag().getTagName());
tagRepo.save(newTag);
dbTag = newTag;
}
newPostTag.setTag(dbTag);
newPostTag.setPost(newPost);
newPost.getPostTags().add(newPostTag);
}
return PostRepository.save(newPost);
}
The above code works first time and creates record in POST & TAG & POSTTAG. But when i run the save again with same input it complains below error,
javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [PostTagId@c03f34a0]
Clearly it says there is already an obj which is there in PostId + TagId combination, But how can i just do update or merge in that case for only PostTag entity extra fields if there is already same combination available?
Please help.