# 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<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集合树结构进行解析,效果如下: