Reputation: 55
@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!
Upvotes: 4
Views: 1202
Reputation: 55
the answer is:
List<Comment> comments = commentRepository.findByParentCommentIsNull();
Upvotes: 0
Reputation: 467
You should use jpa method:
List<Comment> findByChildrenCommentsIsNull();
to get all the root comments and their nested replies.
Upvotes: 3