【问题标题】:Duplicated entities in Bidirection OneToMany relationship when fetching with Spring Data JPA使用 Spring Data JPA 获取时双向 OneToMany 关系中的重复条目
【发布时间】:2019-12-08 21:39:43
【问题描述】:

我定义了两个实体。它们都通过双向@OneToMany 连接。 这是我的两个实体

@Entity(name = "Post")
@Table(name = "post")
public class Post {

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();

    //Constructors, getters and setters removed for brevity

    public void addComment(PostComment comment) {
        comments.add(comment);
        comment.setPost(this);
    }

    public void removeComment(PostComment comment) {
        comments.remove(comment);
        comment.setPost(null);
    }
}

@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {

    @Id
    @GeneratedValue
    private Long id;

    private String review;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "post_id")
    private Post post;

    //Constructors, getters and setters removed for brevity

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof PostComment )) return false;
        return id != null && id.equals(((PostComment) o).getId());
    }
    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

我正在使用 Spring Data JPA 来获取/保存实体。 保存工作正常,例如,如果我保存 1 个帖子和 4 个帖子 cmets,我可以看到数据库中的条目。我使用的数据库是 PostgreSQL。 当我使用 findAll 方法通过我的存储库获取所有帖子时,我会收到带有 4 个 cmets 的帖子。

问题是当我通过 getOne 方法仅获取一篇帖子时,找到了该帖子,但由于某种原因,该实体包含 7 个帖子 cmets。第一项重复 3 次,第二项重复两次。

我不明白为什么会发生这种情况以及如何解决这个问题。 任何帮助表示赞赏。

谢谢

【问题讨论】:

  • 请为此案例在数据库中分享一个具体的数据值
  • 为什么要使用 Object.hash 来生成单个值的哈希码?你可能想要 Objects.hashCode
  • @JamesGawron 我正在使用 Objects.hashCode
  • @CipQuestion 您问题中的代码 sn-p 有 public int hashCode() { return Objects.hash(id); } // 真的不是这样吗?

标签: spring hibernate spring-data-jpa spring-data one-to-many


【解决方案1】:

您需要将 List 更改为 Set。

@OneToMany(mappedBy = "post",cascade = CascadeType.ALL,orphanRemoval = true)
private Set<PostComment> comments = new HashSet<>();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-09
  • 2021-02-10
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 2023-04-09
相关资源
最近更新 更多