使用Spring Data JPA进行获取时,双向OneToMany关系中的重复实体

问题描述 投票:0回答:1

我定义了两个实体。它们都通过双向@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次,第二个重复两次。

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

谢谢

spring hibernate spring-data-jpa spring-data one-to-many
1个回答
0
投票

您需要将列表更改为集合。

@OneToMany(mappedBy = "post",cascade = CascadeType.ALL,orphanRemoval = true)
private Set<PostComment> comments = new HashSet<>();
© www.soinside.com 2019 - 2024. All rights reserved.