论坛实现类似b站评论楼层
思路:
1.先用递归的方式将所有数据查出
2.再用递归的方式将父级评论的子级及其嵌套子级
上代码:
1.递归查询所有评论
实体类 自己写吧
public void recursiveCommonReplyList(List<CourseCommentDto> courseCommonList){
for(CourseCommentDto cd :courseCommonList){
List<CourseCommentDto> courseCommonReplyList = findCourseCommonReplyList(cd.getId());
if(courseCommonReplyList !=null){
cd.setReplyList(courseCommonReplyList);
recursiveCommonReplyList(courseCommonReplyList);
}
}
}
2.再用递归的方式将父级评论的子级及其嵌套子级
public void mergeChildrenList(List<CourseCommentDto> courseCommonList){
for (CourseCommentDto comment : courseCommonList) {
// 防止checkForComodification(),而建立一个新集合
ArrayList<CourseCommentDto> fatherChildren = new ArrayList<>();
// 递归处理子级的回复,即回复内有回复
findChildren(comment, fatherChildren);
// 将递归处理后的集合放回父级的孩子中
comment.setReplyList(fatherChildren);
}
}
/**
* 二层回复 父级评论的子级及其嵌套子级
* **/
public void findChildren(CourseCommentDto parent, List<CourseCommentDto> fatherChildren) {
// 找出直接子级
List<CourseCommentDto> comments = parent.getReplyList();
// 遍历直接子级的子级
for (CourseCommentDto comment : comments) {
// 若非空,则还有子级,递归
if (!comment.getReplyList().isEmpty()) {
findChildren(comment, fatherChildren);
}
// 已经到了最底层的嵌套关系,将该回复放入新建立的集合
fatherChildren.add(comment);
// 容易忽略的地方:将相对底层的子级放入新建立的集合之后
// 则表示解除了嵌套关系,对应的其父级的子级应该设为空
comment.setReplyList(new ArrayList<>());
}
}
缺点:当回复条数太多时 由于子类是由子级嵌套实现 所以无法在mysql层进行分页 分页方法需要重新编写