spring - 使用 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 次,第二个条目重复两次。
我不明白为什么会这样,我该如何解决。任何帮助表示赞赏。
谢谢
解决方案
您需要将列表更改为设置。
@OneToMany(mappedBy = "post",cascade = CascadeType.ALL,orphanRemoval = true)
private Set<PostComment> comments = new HashSet<>();
推荐阅读
- django - 来自 ListBox 的数据发布未呈现到数据库
- c# - 如何更新注释的内容
- angular - 反应式开发 | RxJS 异步管道不工作
- .net - .netcore 应用程序的重复主键数据库条目 mysql 错误
- docker - Docker 映像到期日期
- javascript - 在向 API 发出请求后,如何在从 Mobx 存储访问数据时修复页面的额外渲染?
- corda - HibernateException:在记录事务期间级联期间刷新是危险的
- wordpress - WordPress(元素)
- python - Python 多处理的管理器列表没有锁?
- linear-regression - 无效的语法 erroExpected 2D 数组,得到 1D 数组而不是线性回归