个人博客项目笔记_06

Bug修正

之前Article中的commentCounts,viewCounts,weight 字段为int,会造成更新阅读次数的时候,将其余两个字段设为初始值0。

处理办法:将int改为Integer

java 复制代码
package com.cherriesovo.blog.dao.pojo;

import lombok.Data;

@Data
public class Article {

    public static final int Article_TOP = 1;

    public static final int Article_Common = 0;

    private Long id;

    private String title;

    private String summary;

    private Integer commentCounts;

    private Integer viewCounts;

    /**
     * 作者id
     */
    private Long authorId;
    /**
     * 内容id
     */
    private Long bodyId;
    /**
     *类别id
     */
    private Long categoryId;

    /**
     * 置顶
     */
    private Integer weight;


    /**
     * 创建时间
     */
    private Long createDate;
}
java 复制代码
package com.cherriesovo.blog.vo;


import lombok.Data;

import java.util.List;

@Data
public class ArticleVo {

    private Long id;

    private String title;

    private String summary;

    private Integer commentCounts;

    private Integer viewCounts;

    private Integer weight;
    /**
     * 创建时间
     */
    private String createDate;

    private String author;

    private ArticleBodyVo body;

    private List<TagVo> tags;

    private CategoryVo category;

}

1. 评论列表

sql 复制代码
CREATE TABLE `blog`.`ms_comment`  (
  `id` bigint(0) NOT NULL AUTO_INCREMENT,
  `content` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL,
  `create_date` bigint(0) NOT NULL,
  `article_id` int(0) NOT NULL,
  `author_id` bigint(0) NOT NULL,
  `parent_id` bigint(0) NOT NULL,
  `to_uid` bigint(0) NOT NULL,	#给谁评论
  `level` varchar(1) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,	#第几层评论
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `article_id`(`article_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
java 复制代码
package com.cherriesovo.blog.dao.pojo;

import lombok.Data;
//评论
@Data
public class Comment {

    private Long id;

    private String content;

    private Long createDate;

    private Long articleId;

    private Long authorId;

    private Long parentId;

    private Long toUid;

    private Integer level;
}

1.1 接口说明

接口url:/comments/article/{id}

请求方式:GET

请求参数:

参数名称 参数类型 说明
id long 文章id(路径参数)

返回数据:

json 复制代码
{
    "success": true,
    "code": 200,
    "msg": "success",
    "data": [
        {
            "id": 53,
            "author": {
                "nickname": "李四",
                "avatar": "http://localhost:8080/static/img/logo.b3a48c0.png",
                "id": 1
            },
            "content": "写的好",
            "childrens": [
                {
                    "id": 54,
                    "author": {
                        "nickname": "李四",
                        "avatar": "http://localhost:8080/static/img/logo.b3a48c0.png",
                        "id": 1
                    },
                    "content": "111",
                    "childrens": [],
                    "createDate": "1973-11-26 08:52",
                    "level": 2,
                    "toUser": {
                        "nickname": "李四",
                        "avatar": "http://localhost:8080/static/img/logo.b3a48c0.png",
                        "id": 1
                    }
                }
            ],
            "createDate": "1973-11-27 09:53",
            "level": 1,
            "toUser": null
        }
    ]
}

1.2 Controller

java 复制代码
package com.cherriesovo.blog.controller;

import com.cherriesovo.blog.service.CommentsService;
import com.cherriesovo.blog.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("comments")
public class CommentsController {

    @Autowired
    private CommentsService commentsService;

    @GetMapping("article/{id}")
    public Result comments(@PathVariable("id") Long articleId){

        return commentsService.commentsByArticleId(articleId);

    }
}

1.3 Service

java 复制代码
package com.cherriesovo.blog.service;

import com.cherriesovo.blog.vo.Result;

public interface CommentsService {

    //根据文章id查询所有的评论列表
    Result commentsByArticleId(Long articleId);
}

private UserVo author; //作者信息

private List<CommentVo> childrens;	//子评论

private String createDate;	//时间

private UserVo toUser;	//给谁评论
copy()中除了使用BeanUtils.copyProperties(comment,commentVo)之外,以上四个属性需要手动编写代码设置。
java 复制代码
package com.cherriesovo.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cherriesovo.blog.dao.mapper.CommentMapper;
import com.cherriesovo.blog.dao.pojo.Comment;
import com.cherriesovo.blog.service.CommentsService;
import com.cherriesovo.blog.service.SysUserService;
import com.cherriesovo.blog.vo.CommentVo;
import com.cherriesovo.blog.vo.Result;
import com.cherriesovo.blog.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentsServiceImpl implements CommentsService {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private SysUserService sysUserService;

	public CommentVo copy(Comment comment){
        CommentVo commentVo = new CommentVo();
        BeanUtils.copyProperties(comment,commentVo);
        //1、时间格式化
        commentVo.setCreateDate(new DateTime(comment.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //2、作者信息
        Long authorId = comment.getAuthorId();
        UserVo userVo = this.sysUserService.findUserVoById(authorId);
        commentVo.setAuthor(userVo);
        //3、评论的评论(子评论)
        Integer level = comment.getLevel();
        if(1 == level){
            Long id = comment.getId();
            List<CommentVo> commentVoList = findCommentsByParentId(id);
            commentVo.setChildrens(commentVoList);
        }
        //4、给谁评论
        if (level > 1) {
            Long toUid = comment.getToUid();
            UserVo toUserVo = this.sysUserService.findUserVoById(toUid);
            commentVo.setToUser(toUserVo);
        }
        return commentVo;
    }

    public List<CommentVo> copyList(List<Comment> commentList){
        List<CommentVo> commentVoList = new ArrayList<>();
        for (Comment comment : commentList) {
            commentVoList.add(copy(comment));
        }
        return commentVoList;
    }
    
    //通过父id查询评论列表
    private List<CommentVo> findCommentsByParentId(Long id) {
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getParentId,id);
        queryWrapper.eq(Comment::getLevel,2);
        //SELECT * FROM comment WHERE parent_id = ? AND level = 2
        List<Comment> comments = this.commentMapper.selectList(queryWrapper);
        return copyList(comments);
    }

    
    @Override
    public Result commentsByArticleId(Long articleId) {
        /*
        * 1、根据文章id查询评论列表  从coment表中查
        * 2、根据作者的id查询作者的信息
        * 3、判断如果 level=1 要去查询他有没有子评论
        * 4、如果有,根据评论父id进行查询(parent_id)
        * */
        LambdaQueryWrapper<Comment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Comment::getArticleId,articleId);
        queryWrapper.eq(Comment::getLevel,1);
        //SELECT * FROM comment WHERE article_id = 'articleId' AND level = 1;
        List<Comment> comments = commentMapper.selectList(queryWrapper);
        return Result.success(copyList(comments));
    }
}

返回的数据:

java 复制代码
package com.cherriesovo.blog.vo;

import lombok.Data;

import java.util.List;

@Data
public class CommentVo  {

    private Long id;

    private UserVo author;

    private String content;

    private List<CommentVo> childrens;

    private String createDate;

    private Integer level;

    private UserVo toUser;
}
java 复制代码
package com.cherriesovo.blog.vo;

import lombok.Data;

@Data
public class UserVo {

    private String nickname;

    private String avatar;

    private Long id;
}

在SysUserService中提供 查询用户信息的服务:

java 复制代码
UserVo findUserVoById(Long authorId);
java 复制代码
@Override
    public UserVo findUserVoById(Long authorId) {
        SysUser sysUser = sysUserMapper.selectById(authorId);
        if (sysUser == null){
            sysUser = new SysUser();
            sysUser.setId(1L);
            sysUser.setAvatar("/static/img/logo.b3a48c0.png");
            sysUser.setNickname("码神之路");
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(sysUser,userVo);
        return userVo;
    }

2. 评论

2.1 接口说明

接口url:/comments/create/change

请求方式:POST

请求参数:

参数名称 参数类型 说明
articleId long 文章id
content string 评论内容
parent long 父评论id
toUserId long 被评论的用户id

返回数据:

json 复制代码
{
    "success": true,
    "code": 200,
    "msg": "success",
    "data": null
}

2.2 加入到登录拦截器中

确保评论的时候用户已经登录。

WebMVCConfig:

java 复制代码
@Override
    public void addInterceptors(InterceptorRegistry registry) {
        //当请求路径匹配到 /test 或 /comments/create/change 时,会触发 loginInterceptor 拦截器的拦截操作。
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns("/test")
            	.addPathPatterns("/comments/create/change");
    }

2.3 Controller

将评论请求的参数封装为一个类:

java 复制代码
package com.cherriesovo.blog.vo.params;

import lombok.Data;

@Data
public class CommentParam {

    private Long articleId;

    private String content;

    private Long parent;

    private Long toUserId;
}

CommentsController:

java 复制代码
	@PostMapping("create/change")
    public Result comment(@RequestBody CommentParam commentParam){
        return commentsService.comment(commentParam);
    }

2.4 Service

CommentsServiceImpl只干两件事:

  1. 获取以上字段
  2. 存储到数据库
java 复制代码
  public interface CommentsService {
    Result comment(CommentParam commentParam);
}
java 复制代码
@Service
public class CommentsServiceImpl implements CommentsService {
    @Override
    public Result comment(CommentParam commentParam) {
        //UserThreadLocal 是一个基于 ThreadLocal 实现的工具类,用于在当前线程中存储和获取用户信息
        SysUser sysUser = UserThreadLocal.get();    //拿到登录用户
        Comment comment = new Comment();
        //1、设置文章id
        comment.setArticleId(commentParam.getArticleId());
        //2、设置作者id
        comment.setAuthorId(sysUser.getId());
        //3、设置评论内容
        comment.setContent(commentParam.getContent());
        //4、设置评论时间
        comment.setCreateDate(System.currentTimeMillis());
        Long parent = commentParam.getParent();
        //5、设置评论等级
        if (parent == null || parent == 0) {
            comment.setLevel(1);
        }else{
            comment.setLevel(2);
        }
        //6、设置父id,如果 parent 是 null,则将父级ID设置为 0,否则将其设置为 parent 的值
        comment.setParentId(parent == null ? 0 : parent);
        //7、设置给谁评论
        Long toUserId = commentParam.getToUserId();
        comment.setToUid(toUserId == null ? 0 : toUserId);
        //最后把comment存储到数据库
        this.commentMapper.insert(comment);
        return Result.success(null);
    }
}

处理由于用户id过长导致前端无法解析造成跟评失败的bug

java 复制代码
@Data
public class CommentVo  {
    //防止前端 精度损失 把id转为string
// 分布式id 比较长,传到前端 会有精度损失,必须转为string类型 进行传输,就不会有问题了
    @JsonSerialize(using = ToStringSerializer.class)
    private Long id;

    private UserVo author;

    private String content;

    private List<CommentVo> childrens;

    private String createDate;

    private Integer level;

    private UserVo toUser;
}

Caused by: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Out of range value for column 'article_id' at row 1

解决方法:将数据库中的ms_comment表中的article_id类型修改为bigint

相关推荐
xlsw_2 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭3 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
李小白664 小时前
Spring MVC(上)
java·spring·mvc
Lojarro6 小时前
【Spring】Spring框架之-AOP
java·mysql·spring
zjw_rp7 小时前
Spring-AOP
java·后端·spring·spring-aop
cmdch20179 小时前
Mybatis加密解密查询操作(sql前),where要传入加密后的字段时遇到的问题
数据库·sql·mybatis
王ASC10 小时前
SpringMVC的URL组成,以及URI中对/斜杠的处理,解决IllegalStateException: Ambiguous mapping
java·mvc·springboot·web
撒呼呼10 小时前
# 起步专用 - 哔哩哔哩全模块超还原设计!(内含接口文档、数据库设计)
数据库·spring boot·spring·mvc·springboot
天使day11 小时前
SpringMVC
java·spring·java-ee
秋恬意12 小时前
什么是MyBatis
mybatis