繁体   English   中英

保存成功但更新失败 - 多对多 Spring JPA 使用 Jointable 额外列

[英]Save successful but Update failed - Many to Many Spring JPA with extra column using Jointable

使用 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 & TAG & POSTTAG 中创建记录。 但是当我使用相同的输入再次运行保存时,它会抱怨以下错误,

javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [PostTagId@c03f34a0]

显然它说 PostId + TagId 组合中已经有一个 obj,但是如果已经有相同的组合可用,我怎么能只为 PostTag 实体额外字段进行更新或合并?

请帮忙。

下一个链接上已经有相同的问题,所以它可能对您有所帮助:回答

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM