首页 > 解决方案 > 使用 Spring Data JPA 获取时双向 OneToMany 关系中的重复实体

问题描述

我定义了两个实体。它们都通过双向@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 个帖子评论,我可以看到数据库中的条目。我使用的数据库是 PostgreSQL。当我使用 findAll 方法通过我的存储库获取所有帖子时,我会收到带有 4 条评论的帖子。

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

我不明白为什么会这样,我该如何解决。任何帮助表示赞赏。

谢谢

标签: springhibernatespring-data-jpaspring-dataone-to-many

解决方案


您需要将列表更改为设置。

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

推荐阅读