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

JAVA实现评论功能设计开发

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

202011031206579.png

思路:

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<CommentDetailsDto> commentDetailsListChild;
}

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

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

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

    if (CollectionUtils.isNotEmpty(commentDetailsDtos)) {
        Map<Long, List<CommentDetailsDto>> 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集合树结构进行解析,效果如下:
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值