Spring Boot + vue-element 开发个人博客项目实战教程(十一、文章分类功能实现)

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

前言

前面我们已经把用户功能完成了,包括接入Swagger文档、代码接口调试等操作,基础的东西还是要经常的练习,接下来我们要完成博客文章的分类功能,正如我们在创建文章的时候会选择文章属于哪一类,是Java还是C还是前端等相关的文章,这个需要我们进行单独的管理,尽量减少多表的关联。

一、分页插件Pagehelper

由于分类可能比较多,我们页面不可能全部展示出来,所以我们要使用数据分页,目的就是使数据不全部展示出来,影响页面的美观和布局,分页重要的就是第几页和一页展示几条数据的展示,由于我们使用的是Mybatis所以我们来借助它的分页插件来完成分页,首先要将分页插件引入到我们项目中。 官方网址:github.com/pagehelper/…

1、引入依赖

我们把下面的依赖复制到pom.xml文件中添加依赖,别忘了刷新Maven

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.4.0</version>
</dependency>
复制代码

在这里插入图片描述

如果下载不下来的话还可以手动下载jar包进行引入。你可以从下面的地址中下载最新版本的 jar 包

oss.sonatype.org/content/rep…

repo1.maven.org/maven2/com/…

由于使用了sql 解析工具,你还需要下载 jsqlparser.jar(需要和PageHelper 依赖的版本一致) :

repo1.maven.org/maven2/com/…

2、配置分页插件

然后到我们的配置文件application.yml中添加分页插件的配置。

pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
复制代码

在这里插入图片描述 现在我们就可以在我们的项目中使用了。

3、分页请求类封装

我们将这个请求的类进行封装,因为这个是公共的分页请求,在以后的功能中还会用到,所以我们将请求类进行分装,这个是前端给我们传过来的参数,一共就两个属性,一个是页数,另一个是一页的数量。 我们在工具包config包中再建一个page包,然后把分页的类放在这个page包中。 新建一个请求类:PageRequest.java

package com.blog.personalblog.util;

import lombok.Data;

/**
 * 分页请求
 *
 * @author: SuperMan
 * @create: 2021-11-22
 */
@Data
public class PageRequest {

    /**
     * 页码
     */
    private int pageNum;

    /**
     * 每页的数据条数
     */
    private int pageSize;
}
复制代码

4、分页返回类封装

我们在page包下再建一个返回类,主要放我们分页查询返回的数据。 新建一个分页返回类:PageResult.java

package com.blog.personalblog.config.page;

import lombok.Data;
import java.util.List;

/**
 * 分页返回类
 * 
 * @author: SuperMan
 * @create: 2021-11-22
 */
@Data
public class PageResult {
    /**
     * 当前页码
     */
    private int pageNum;
    /**
     * 每页数量
     */
    private int pageSize;
    /**
     * 记录总数
     */
    private long totalSize;
    /**
     * 页码总数
     */
    private int totalPages;

    /**
     * 存放返回数据
     */
    private List<?> result;

}
复制代码

二、分类功能代码实现

总的添加的类如下: 在这里插入图片描述

1、添加实体类

首先新建一个分类的实体类为:Category.java类,代码和数据库字段对应即可。

package com.blog.personalblog.entity;

import lombok.Data;

import java.time.LocalDateTime;

/**
 * 博客分类
 *
 * @author: SuperMan
 * @create: 2021-11-21
 */
@Data
public class Category {

    /**
     * 主键id
     */
    private Integer categoryId;

    /**
     * 分类名称
     */
    private String categoryName;

    /**
     * 创建时间
     */
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    private LocalDateTime updateTime;

}

复制代码

2、添加业务接口

和用户的一样,在我们创建的service包中,创建一个CategoryService.java类,具体干嘛的可以去看用户实现的那一篇,我这里不再多说,现在主要是多写代码。

package com.blog.personalblog.service;

import com.blog.personalblog.entity.Category;
import com.blog.personalblog.config.page.PageRequest;
import java.util.List;

/**
 * 博客分类实现接口
 *
 * @author: SuperMan
 * @create: 2021-11-21
 */
public interface CategoryService {

    /**
     * 获取所有的分类(分页)
     * @return
     */
    List<Category> getCategoryPage(PageRequest pageRequest);

    /**
     * 新建分类
     * @param category
     * @return
     */
    int saveCategory(Category category);

    /**
     * 修改分类
     * @param category
     * @return
     */
    int updateCategory(Category category);

    /**
     * 删除分类
     * @param categoryId
     */
    void deleteCategory(Integer categoryId);

    /**
     * 根据分类id查找分类
     * @param categoryId
     * @return
     */
    Category findById(Integer categoryId);

}
复制代码

3、添加业务接口实现类

然后和用户一样,在Impl包中新建一个接口的实现类为CategoryServiceImpl.java,主要实现的分类管理的增删改查等操作。基本上和用户表的一样就是查询是分页查询要注意。

package com.blog.personalblog.service.Impl;

import com.blog.personalblog.entity.Category;
import com.blog.personalblog.mapper.CategoryMapper;
import com.blog.personalblog.service.CategoryService;
import com.blog.personalblog.config.page.PageRequest;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 博客分类实现类
 *
 * @author: SuperMan
 * @create: 2021-11-21
 */

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public List<Category> getCategoryPage(PageRequest pageRequest) {
        int pageNum = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNum,pageSize);
        List<Category> categoryList = categoryMapper.getCategoryPage();
        return categoryList;
    }

    @Override
    public int saveCategory(Category category) {
        return categoryMapper.create(category);
    }

    @Override
    public int updateCategory(Category category) {
        return categoryMapper.update(category);
    }

    @Override
    public void deleteCategory(Integer categoryId) {
        categoryMapper.delete(categoryId);
    }

    @Override
    public Category findById(Integer categoryId) {
        Category category = categoryMapper.getById(categoryId);
        if (category == null) {
            return null;
        }
        return category;
    }
}

复制代码

这个里面重点就是分页的接口实现,通过我们前端传过来的两个值,使用PageHelper插件进行分页。不懂得可以去官方文档看看。

4、数据库查询接口实现

紧接着我们在mapper包中新建一个分类的mapper。 CategoryMapper.java

package com.blog.personalblog.mapper;

import com.blog.personalblog.entity.Category;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 博客分类数据接口
 *
 * @author: SuperMan
 * @create: 2021-11-21
 */

@Repository
public interface CategoryMapper {

    /**
     * 创建
     * @param category
     * @return
     */
    int create(Category category);

    /**
     * 修改
     * @param category
     * @return
     */
    int update(Category category);

    /**
     * 分类列表(分页)
     * @return
     */
    List<Category> getCategoryPage();

    /**
     * 删除
     * @param id
     */
    void delete(Integer id);

    /**
     * 根据id查找分类
     * @param id
     * @return
     */
    Category getById(Integer id);

}
复制代码

5、编写数据库xml

我们在resources文件下的mapper文件夹中新建一个CategoryMapper.xml文件。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.blog.personalblog.mapper.CategoryMapper">
    <resultMap id="BaseResultMap" type="com.blog.personalblog.entity.Category">
        <result column="category_id" jdbcType="INTEGER" property="categoryId"/>
        <result column="category_name" jdbcType="VARCHAR" property="categoryName"/>
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime"/>
        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime"/>
    </resultMap>

    <select id="getCategoryPage" resultMap="BaseResultMap">
        select * from person_category
    </select>

    <insert id="create" parameterType="com.blog.personalblog.entity.Category" useGeneratedKeys="true" keyProperty="categoryId">
        INSERT INTO person_category (category_name)
        VALUES(#{categoryName})
    </insert>

    <update id="update" parameterType="com.blog.personalblog.entity.Category">
        update person_category
        <set>
            category_name = #{categoryName}
        </set>
        WHERE category_id = #{categoryId}
    </update>

    <delete id="delete" parameterType="java.lang.Integer">
        delete from person_category where category_id = #{categoryId, jdbcType=INTEGER}
    </delete>

    <select id="getById" resultType="com.blog.personalblog.entity.Category">
        select category_id from person_category where category_id = #{categoryId}
    </select>

</mapper>
复制代码

6、编写接口层

最后写我们的controller层,这里我们先对分页返回的数据进行处理一下,我们在util包中新建一个分页工具为:PageUtil.java

package com.blog.personalblog.util;

import com.blog.personalblog.config.page.PageRequest;
import com.blog.personalblog.config.page.PageResult;
import com.github.pagehelper.PageInfo;

/**
 * 分页工具类
 *
 * @author: SuperMan
 * @create: 2021-11-22
 */
public class PageUtil {

    /**
     *  分页信息封装
     * @param pageRequest
     * @param pageInfo
     * @return
     */
    public static PageResult getPageResult(PageRequest pageRequest, PageInfo<?> pageInfo){
        PageResult pageResult = new PageResult();
        pageResult.setPageNum(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotalSize(pageInfo.getTotal());
        pageResult.setTotalPages(pageInfo.getPages());
        pageResult.setResult(pageInfo.getList());
        return pageResult;
    }

}

复制代码

这个主要是把返回的数据都封装到PageResult返回类中,里面含有分页的信息和数据列表。 接下来编写我们的controller,基本上和用户的一样,除了分页的列表。别忘了加上Swagger接口。

package com.blog.personalblog.controller;

import com.blog.personalblog.entity.Category;
import com.blog.personalblog.service.CategoryService;
import com.blog.personalblog.util.JsonResult;
import com.blog.personalblog.config.page.PageRequest;
import com.blog.personalblog.config.page.PageResult;
import com.blog.personalblog.util.PageUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 分类管理接口
 * 
 * @author: SuperMan
 * @create: 2021-11-21
 */
@Api(tags = "分类管理")
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    /**
     * 分页查询列表
     * @param pageRequest
     * @return
     */
    @PostMapping("list")
    public JsonResult<Object> listPage(@RequestBody @Valid PageRequest pageRequest) {
        List<Category> categoryList = categoryService.getCategoryPage(pageRequest);
        PageInfo pageInfo = new PageInfo(categoryList);
        PageResult pageResult = PageUtil.getPageResult(pageRequest, pageInfo);
        return JsonResult.success(pageResult);
    }

    /**
     * 添加分类
     * @return
     */
    @ApiOperation(value = "添加分类")
    @PostMapping("/create")
    public JsonResult<Object> categoryCreate(@RequestBody @Valid Category category) {
        int isStatus = categoryService.saveCategory(category);
        if (isStatus == 0) {
            return JsonResult.error("添加分类失败");
        }
        return JsonResult.success();
    }

    /**
     * 修改分类
     * @return
     */
    @ApiOperation(value = "修改分类")
    @PostMapping("/update")
    public JsonResult<Object> categoryUpdate(@RequestBody @Valid Category category) {
        int isStatus = categoryService.updateCategory(category);
        if (isStatus == 0) {
            return JsonResult.error("修改分类失败");
        }
        return JsonResult.success();
    }

    /**
     * 删除
     * @return
     */
    @ApiOperation(value = "删除分类")
    @PostMapping("/delete/{id}")
    public JsonResult<Object> categoryDelete(@PathVariable(value = "id") int id) {
        categoryService.deleteCategory(id);
        return JsonResult.success();
    }

}
复制代码

三、测试

分类功能功能已经实现,接下来大家可以自己用postman进行测试这四个接口是否有错误,和用户的基本一致。 这里我只说明一下查询的接口,我们需要传入两个参数。

在这里插入图片描述

大家多添加几条分类进行分页测试。好啦,这一篇就到这里了,文章分类功能已经基本上完成。添加、修改、删除留给大家自己测一测。麻烦大家给点点赞啊!来点动力哈哈

在这里插入图片描述

上一篇:Spring Boot + vue-element 开发个人博客项目实战教程(十、调试、密码加密和Swagger接口文档) 下一篇:Spring Boot + vue-element 开发个人博客项目实战教程(十二、通知公告功能实现)

猜你喜欢

转载自juejin.im/post/7129744939574886414