效果图
数据库设计
还可以使用路径模块 一级评论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);
}
}