I. demand
The existing requirement is to show all comments of a post.
Two: analysis
Comments on posts are divided into main comments and sub comments. Main comments are direct comments on posts, and sub comments are comments on comments.
Three: train of thought
First, get all the main comments of a post, recursively judge whether there are sub comments, and get sub comments.
Four: coding
Entity class:
1 import java.util.Date; 2 import java.util.List; 3 4 import com.fasterxml.jackson.annotation.JsonFormat; 5 6 import lombok.Data; 7 @Data 8 public class BsChannelPostReply { 9 private long replyId; 10 private String niceName; 11 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") 12 private Date replyDate; 13 private String content; 14 private long directRepliedId;//Direct comment of reply replyId 15 private List<BsChannelPostReply> children;//The following sub comments 16 }
Get the main comment list and recurse all the sub comments:
1 @Override 2 @Datasource(value="community")//Switch data source 3 public List<BsChannelPostReply> getMainReply(int postId) { 4 // TODO Auto-generated method stub 5 List<BsChannelPostReply> listMain=dao.getMainReply(postId);//Get main comment 6 if(listMain.size()>=0){//If the main comment is not empty 7 for (BsChannelPostReply bsChannelPostReply : listMain) { 8 bsChannelPostReply.setChildren(getMainReplyChildren(bsChannelPostReply.getReplyId()));//Load subcomments 9 } 10 } 11 return listMain; 12 } 13 14 @Override 15 @Datasource(value="community")//Switch data source 16 public List<BsChannelPostReply> getMainReplyChildren(long replyId) { 17 // TODO Auto-generated method stub 18 List<BsChannelPostReply> listChildren=dao.getMainReplyChildren(replyId);//Based on the current replayId Get current level sub comment list 19 if(listChildren.size()>=0){ 20 for (BsChannelPostReply bsChannelPostReply : listChildren) { 21 bsChannelPostReply.setChildren(getMainReplyChildren(bsChannelPostReply.getReplyId()));//When judging whether there are sub comments in the current sub comment, call recursively until there are no sub comments 22 } 23 } 24 return listChildren; 25 }
Five: effect
According to this kind of recursive call, we can get unlimited sub comment list theoretically.