4
@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> {
}

Here is how I am saving replies for a specific comment.

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);

When I do commentrepository.findAll()

I would like to return the following json data.

{
 "id": 1,
 "content": "1 comment",
 "replies" :[
 {
 "id": 2,
 "content": "reply 1 to comment 1"
 },
 {
 "id": 3,
 "content": "reply 2 to comment 1"
 }
 ]
 }

My goal is to build a reddit style comment system. Where each comment has an array of comments(replies). When I query for all comments, using spring data jpa, I only want the root comments and their nested replies.

In the above case, don't want something like this:

{
 {
 "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"
 }
}

I have spent several days on this without success. I have tried using @jsonIgnore and other jackson annotations without success. Any suggestions or recommendations? Thank you in adavance. you are appreciated!

asked Feb 6, 2019 at 4:51

2 Answers 2

3

You should use jpa method:

List<Comment> findByChildrenCommentsIsNull();

to get all the root comments and their nested replies.

answered Feb 6, 2019 at 7:25
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the hint. What I actually wanted is commentRepository.findByParentCommentIsNull();
0

the answer is:

List<Comment> comments = commentRepository.findByParentCommentIsNull();
answered Feb 7, 2019 at 0:08

1 Comment

Dont just include the code. Kindly explain how your answer will solve the issue.Try to follow stackoverflow.com/help/how-to-answer

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.