最近需要做一个评论功能。除了显示评论外,还需要显示评论回复和对评论的回复。这里使用了多级注释的递归实现。评论实体数据库存储字段:id评论id,parent_id回复评论id,message消息。其中,如果评论不是回复评论,parent_id为-1。创建评论实体Comment:publicclassComment{/***id*/privateIntegerid;/***父类id*/privateIntegerparentId;/***message*/privateStringmessage;}查询所有评论数据。方便显示树数据,添加回复列表到CommentListchildrenViewComment结构如下://显示树数据publicclassViewComment{/***id*/privateIntegerid;/***父类id*/privateIntegerparentId;/***消息*/私有字符串消息;/***回复列表*/privateListchildren=newArrayList<>();}添加非回复评论非回复评论的parent_id为-1,先找到非回复评论:ListviewCommentList=newArrayList<>();//添加模拟数据Commentcomment1=newComment(1,-1,"Message1");Commentcomment2=newComment(2,-1,"Message2");Commentcomment3=newComment(3,1,"留言3,回复留言1");留言comment4=newComment(4,1,"留言4,回复留言1");留言comment5=newComment(5,2"消息5,回复消息2");评论comment6=newComment(6,3,"消息6,回复消息3");//添加一条不回复的评论(评论评论:commentList){if(comment.getParentId()==-1){ViewCommentviewComment=newViewComment();BeanUtils.copyP权限(评论,viewComment);viewCommentList.add(viewComment);}}递归添加回复评论遍历每条未回复的评论,递归添加回复评论:Commentcomment:commentList){//找到匹配的parentIdif(rootViewComment.getId().equals(comment.getParentId())){ViewCommentviewComment=newViewComment();BeanUtils.copyProperties(评论,viewComment);rootViewComment.getChildren().add(viewComment);//递归调用add(viewComment,commentList);}}}遍历每条未回复评论未回复评论id匹配评论parentId,添加到评论的子列表中。递归调用。结果展示:github源码https://github.com/jeremylai7/java-codes/tree/master/basis/src/main/java/recurve