@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 data 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 和其他 jackson 注释但没有成功。有什么建议或建议吗? 提前谢谢你。不胜感激!
最佳答案
你应该使用 jpa 方法:
List<Comment> findByChildrenCommentsIsNull();
获取所有根评论及其嵌套回复。
关于java - Spring boot JPA Hibernate 返回嵌套的 Json 对象 : Reddit style comment system,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54546804/