java - Spring boot JPA Hibernate 返回嵌套的 Json 对象 : Reddit style comment system

标签 java spring hibernate spring-boot spring-data-jpa

@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/

相关文章:

java - 将字符串空格后的第一个字符大写如果完整的句子是大写java

java - 在 googleApps 中使用 java 将用户添加到组织部门

Spring 集成: How does RendezvousChannel work?

java - Hibernate 二级缓存 : Does get use it?

java - 在 Extjs 中,在 Grid 中更新时,如果 session 超时如何重定向到登录页面?

java - 如何知道与主题关联的 session 在java shiro中是否已过期

java - [JAVA]如何创建排名系统并将其保存到.txt 文件?

java - 为什么在Controller注解中使用@Component

java - 如何在Spring中使用@PropertySource加载的属性文件中配置 'dynamic key'

mysql - 使用 Hibernate 实现 JWT Spring 安全 token 存储?