栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

# JAVA实现评论功能设计开发

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

# JAVA实现评论功能设计开发

JAVA实现评论功能设计开发

实现类似微信朋友圈的评论楼层

思路:

1、嵌套型的评论方式所需要的数据结构是树状型的,评论多起来的话层级结构会变得很复杂

实现原理为在评论表之中添加一个【parent_id】字段,定义评论和回复为父子级的关系,评论为父级,回复为子级,默认为【0】,表示为没有父级

create table `comment` (
     `id` int(11) not null auto_increment comment '主键id',
     `nickname` varchar(255) default null comment '评论者昵称',
     `avatar` varchar(255) comment '评论头像',
     `content` varchar(255) default null comment '评论的内容',
     `blog_id` int(11) default null comment '评论的博客id',
     `parent_id` int(11) default '-1' comment '父级评论id',
     primary key (`id`)
 ) comment '评论表';

DTO 设计如下:

public class CommentDetailsDto implements Serializable {

    @ApiModelProperty("id")
    private Long id;

    @ApiModelProperty("上级评论id")
    private Long pid;

    @ApiModelProperty("上级评论名称")
    private String repliedName;

    @ApiModelProperty("评论用户id")
    private Long userId;
    
    @ApiModelProperty("用户头像")
    private String userPicture;

    @ApiModelProperty("子回复")
    private List commentDetailsListChild;
}

2、需要使用stream流的groupingBy工具,将查出来的所有评论根据parent_id进行分组,生成一个以parent_id作为Key,评论记录集合为value的map结构

​ 循环遍历评论记录,根据Id去map集合中去查找相关子回复List集合,如果没有则设置为null

    list = commentDetailsRepository.list(map);
    List commentDetailsDtos = CommentDetails.fromModelList(list);

    if (CollectionUtils.isNotEmpty(commentDetailsDtos)) {
        Map> zoneByParentIdMap = commentDetailsDtos.stream().collect(Collectors.groupingBy(CommentDetailsDto::getPid));
        commentDetailsDtos.forEach(regionTree -> {
            regionTree.setCommentDetailsListChild(zoneByParentIdMap.get(regionTree.getId()));
            CommentDetails commentDetails = commentDetailsRepository.findById(regionTree.getPid());
            if (CollectionUtils.isEmpty(regionTree.getCommentDetailsListChild())){
                regionTree.setCommentDetailsListChild(new ArrayList<>());
            }
        });
        commentDetailsDtos = commentDetailsDtos.stream().filter(v -> v.getPid() == 0).collect(Collectors.toList());
        }

3、前端可通过控件对该List集合树结构进行解析,效果如下:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/532340.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号