1. 数据库结构
字段名 | 类型 | 注释 |
---|---|---|
comment_id | bigint | 主键id |
user_Id | bigint | 用户id |
blog_id | bigint | 博客文章id |
reply_user_Id | bigint | 被回复用户id |
pid | bigint | 父id |
comment_msg | varchar | 回复内容 |
creat_time | varchar | 创建时间 |
其中 pid=0 时,为一级评论,一级评论的 reply_user_id 也为 0
创建评论form
public class CreatCommentForm {
@ApiModelProperty("博客Id")
@NotNull(message = "博客id不能为空")
private Long blogId;
@ApiModelProperty("评论内容")
@NotNull(message = "评论内容不能为空")
private String commentMsg;
@ApiModelProperty("被回复人 ")
private Long replyUserId;
@ApiModelProperty("父级评论Id 若为首级评论则为0")
@NotNull(message = "父级评论Id不能为空")
private Long pid;
}
Service层实现代码
- 创建评论
@Override
public ResultVO creatComment(CreatCommentForm form) {
Comment comment = new Comment();
BeanUtils.copyProperties(form, comment);
if (comment.getReplyUserId() == null) {
comment.setReplyUserId(0L);
}
// 获取当前用户
User user = userService.getCurrentUser();
if (user == null) {
return ResultVOUtil.error(ResultEnum.USER_NOT_LOGIN);
}
comment.setUserId(user.getUserId());
comment.setCreatTime(TimeUtil.getNowTime());
if (insert(comment)) {
// 评论数目加1
addComments(comment.getBlogId());
return ResultVOUtil.success(comment);
}
return ResultVOUtil.error(ResultEnum.SERVER_ERROR);
}
创建评论包括:创建一级评论和创建一级评论下的子评论,通过 pid 和 reply_user_id 来区分
查看所有评论返回VO
public class CommentVO {
private Long commentId;
private Long userId;
private String userName;
private String headPortrait;
private String creatTime;
private String commentMsg;
private List<ReplyVO> replyVO;
}
子评论VO
public class ReplyVO {
private Long commentId;
private Long userId;
private String userName;
private String headPortrait;
private Long replyUserId;
private String replyUserName;
private String creatTime;
private String commentMsg;
}
查看所有评论service
public List<CommentVO> getAllCommentByBlogId(Long blogId) {
List<CommentVO> result = new ArrayList<>();
// 查找文章下所有的父级评论
List<Long> commentIdList = commentMapper.getCommentIdByBlogId(blogId);
for (Long commentId : commentIdList) {
CommentVO vo = commentMapper.selectCommentById(commentId);
//查找所有父级评论下的子评论
List<ReplyVO> vos = commentMapper.selectByPid(vo.getCommentId());
List<ReplyVO> reply = new ArrayList<>();
for (ReplyVO replyVO : vos) {
// 添加被回复人的用户名
User user = userService.selectByUserId(replyVO.getReplyUserId());
replyVO.setReplyUserName(user.getUsername());
reply.add(replyVO);
}
vo.setReplyVO(reply);
result.add(vo);
}
return result;
}
效果图如下
第二层即所有子评论的pid都为当前第一层(父评论)的 comment_id,第二层通过reply_user_id来区分被回复人是谁。返回的JSON格式如下
博客年底前上线,源码同步更新中 github地址