自学内容网 自学内容网

Java SpringBoot 若依 后端实现评论“盖楼“,“楼中楼“功能 递归查询递归组装评论结构

效果图

在这里插入图片描述

数据库设计

还可以使用路径模块 一级评论id,二级评论id, 用like最左匹配原则查询子评论
因为接手遗留代码,需要添加字段,改动数据库,我就不改动了,导致我下面递归查询子评论不是很好。

在这里插入图片描述

业务代码

    @Override
    public List<SubReviewForm> getSubReviewForms(String publishingId, String creatorId, String sort, String type, String systemType) {

        //查询一级评论
        SubReviewForm querySubReviewForm = new SubReviewForm();
        querySubReviewForm.setSubPublishingParentId(publishingId);
        //只看楼主
        if (StringUtils.isNotBlank(creatorId)) {
            querySubReviewForm.setCreatorId(creatorId);
        }
        PageUtils.startPage();
        List<SubReviewForm> list = subReviewFormMapper.getObjList(querySubReviewForm, sort, null);
        if (CollectionUtils.isEmpty(list)) {
            return list;
        }
        //递归查询二级评论以及子评论
        List<String> ids = list.stream().map(SubReviewForm::getId).collect(Collectors.toList());
        List<SubReviewForm> subReviewFormList = recursiveQuerySubReviewForm(ids);

        //递归组装楼层
        recursiveAssembleSubReviewForm(list,subReviewFormList);
}
    /**
     * 递归查询评论
     *
     */
    public List<SubReviewForm> recursiveQuerySubReviewForm(List<String> ids) {
        List<SubReviewForm> subReviewFormList = subReviewFormMapper.getReviewBySubPublishingParentId(ids);
        if (CollectionUtils.isEmpty(subReviewFormList)) {
            subReviewFormList = new ArrayList<>();
        } else {
            // 递归获取楼层
            List<String> newIds = subReviewFormList.stream().map(SubReviewForm::getId).collect(Collectors.toList());
            subReviewFormList.addAll(recursiveQuerySubReviewForm(newIds));
        }
        return subReviewFormList;
    }

    /**
     * 递归组装评论楼层
     *
     */
    private void recursiveAssembleSubReviewForm(List<SubReviewForm> rootList, List<SubReviewForm> subList) {
        for (SubReviewForm reviewForm : rootList) {
            for (SubReviewForm subReviewForm : subList) {
                //一级评论
                if (StringUtils.equals(reviewForm.getId(), subReviewForm.getSubPublishingParentId()) ||
                        //二级评论以及子评论
                        StringUtils.equals(reviewForm.getSubPublishingId(), subReviewForm.getSubPublishingParentId())) {
                    reviewForm.getChildren().add(subReviewForm);
                }
            }
            recursiveAssembleSubReviewForm(reviewForm.getChildren(), subList);
        }
    }

原文地址:https://blog.csdn.net/qq_43751489/article/details/140398210

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!