** 最近再开发个人的网站的时候,想到了多级评论,在简单的学习了一下之后,认识到数据库设计的重要性,对此,总结一下多级评论的实现 **
数据库设计
CREATE TABLE `comment` (
`id` int(11) ,
`foreign_id` int(11) '业务模块的id',
`content` varchar(255) '内容',
`username` varchar(20) '用户名称',
`user_id` int(11) '用户id',
`pid` int(11) '父级评论id',
`target` varchar(255) '回复对象',
`createtime` datetime '创建时间',
)
我们通常使用单表来实现多级评论
例如,在某个Post下评论,我们通常讲postId 记录在foreign_id下,当我直接回复Post本身时,我们将Pid记为空,当我们回复某个Post下的某个评论时,我们将Pid记为回复评论的Id,这样我们就可以实现多级评论。
pojo层设计
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer foreignId;
private String content;
private String username;
private Integer userId;
private Integer pid;
private String target;
private DateTime createtime;
@Transient //表示数据中不存在
private List<Comment> children;
}
在设计pojo层时,我们需要新增一个children作为此父级评论的子级评论的List
service层设计
Map<String, Object> map = new HashMap<>();
List<Comment> comments = commentDao.findAllByForeignId(foreignId);
//mapper层中查找所有foreignId下的评论
List<Comment> rootComments = comments.stream().filter(comment -> comment.getPid() == null).collect(Collectors.toList());
// 使用stream() 将rootComments过滤成父级评论
for (Comment rootComment : rootComments) {
rootComment.setChildren(comments.stream().filter(comment -> rootComment.getId().equals(comment.getPid())).collect(Collectors.toList()));
}
//将 rootComment.getId() == comment.getPid() 匹配的放入ChildrenList
map.put("comments", rootComments);
return map;
上面就是自己总结的实现多级评论的方式,个人认为比较容易理解和使用