@Entity
public class Comment {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String content;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "parent_id")
private Comment parentComment;
@OneToMany(mappedBy="parentComment", cascade = CascadeType.ALL)
private List<Comment> childrenComments = new ArrayList<>();
}
public interface CommentRepository extends JpaRepository<Comment, Long> {
}
这是我保存对特定评论的回复的方式。
Comment parent = new Comment();
parent.setContent(" 1 comment");
parent = commentRepository.save(parent);
Comment reply1 = new Comment();
reply1.setContent("reply 1 to comment 1");
reply1.setParentComment(parent);
Comment reply2 = new Comment();
reply1.setContent("reply 2 to comment 1");
reply1.setParentComment(parent);
parent = commentRepository.save(parent);
当我做commentrepository.findAll()
我想返回以下json数据。
{
"id": 1,
"content": "1 comment",
"replies" :[
{
"id": 2,
"content": "reply 1 to comment 1"
},
{
"id": 3,
"content": "reply 2 to comment 1"
}
]
}
我的目标是建立Reddit风格的评论系统。每个评论都有一个评论数组(回复)。当我使用spring数据jpa查询所有评论时,我只想要根评论及其嵌套的回复。
在上述情况下,不要这样的东西:
{
{
"id": 1,
"content": "1 comment",
"replies" :[
{
"id": 2,
"content": "reply 1 to comment 1"
},
{
"id": 3,
"content": "reply 2 to comment 1"
}
]
}
{
"id": 2,
"content": "reply 1 to comment 1"
}
{
"id": 2,
"content": "reply 1 to comment 1"
}
}
我花了几天没有成功。我尝试使用@jsonIgnore和其他杰克逊注释未成功。有什么建议或建议吗? 谢谢你的配合。您很感激!
答案 0 :(得分:2)
您应该使用jpa方法:
List<Comment> findByChildrenCommentsIsNull();
获取所有根注释及其嵌套的回复。
答案 1 :(得分:0)
答案是:
List<Comment> comments = commentRepository.findByParentCommentIsNull();