java保存成功,但更新失败使用Jointable的多对多Spring JPA和额外列
使用PostRepository保存方法,使用以下方法更新现有实体时出错
这是我的物品
@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
}
我尝试将帖子保存为下面的post json格式
{
"postId": "post-001",
"postName": "post-001",
"postTags": [
{
"tag": {
"tagId": "tag-001",
"tagName": "tag-001"
}
}
]
}
服务实现如下所示:
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);
}
上述代码第一次工作,并在POST&;中创建记录;标签及标签;邮戳。 但当我使用相同的输入再次运行save时,它会出现以下错误
javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [PostTagId@c03f34a0]
显然,它说已经有一个obj存在于PostId+TagId组合中, 但是,如果已经有相同的组合可用,那么在这种情况下,如何仅对PostTag实体额外字段执行更新或合并呢
请帮忙
# 1 楼答案
下一个链接上已经有相同的问题,所以它可能会帮助您:answer