欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot整合mybatis使用三:使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块

程序员文章站 2021-11-23 10:49:01
文章目录前言一、maven依赖1. 新增依赖(本博客用到的swagger2和分页依赖)2. 所有依赖二、application.yml配置1. 新增配置2. 全配置3. 打印SQL日志配置(两种)四、统一的数据返回格式1. 定义统一数据返回格式(important)2. DataResult.java4. ResponseCodeInterface.java 接口3. BaseResponseCode.java枚举类五、请求模块1. vo/req/StudentPageReqVo.java2. vo/res...

前言

一、maven依赖

1. 新增依赖(本博客用到的swagger2和分页依赖)

<!--swagger2 依赖-->
<!--http://localhost:8086/swagger-ui.html# 使用这个接口对接口进行测试-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

<!--分页依赖-->
<dependency>
    <groupId>com.github.jsqlparser</groupId>
    <artifactId>jsqlparser</artifactId>
    <version>1.0</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.5</version>
</dependency>

2. 所有依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.feng</groupId>
    <artifactId>springboot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mybatis</name>
    <description>springboot-mybatis</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>


        <!-- mybatis逆向工程jar包:mybatis-generator-core -->
        <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-maven-plugin -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--逆向工程,自动生成@Table、@Id等注解,会使用到下面两个注解-->
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>
        <!--通用Mapper启动器-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.3</version>
        </dependency>

        <!--第一次新增加:mysql驱动和Druid数据源-->
        <!--数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--数据源-->
        <!--http://localhost:8083/druid/index.html 通过这个网址 对 SQL进行监控-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <!--第二次新增加:swagger2、jsqlparser、pagehelper-->
        <!--swagger2 依赖-->
        <!--http://localhost:8086/swagger-ui.html# 使用这个接口对接口进行测试-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!--分页依赖-->
        <dependency>
            <groupId>com.github.jsqlparser</groupId>
            <artifactId>jsqlparser</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>


    </dependencies>

    <build>
        <finalName>springboot-mybatis</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <overwrite>true</overwrite>
                    <configurationFile>src/main/resources/mybatis-generator/generatorConfig.xml</configurationFile>
                    <!--避免操作不当,覆盖原来的类,设置为不覆盖:false-->
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.47</version>
                    </dependency>
                    <!--<dependency>
                        <groupId>com.thunisoft.arterybase</groupId>
                        <artifactId>ArteryBase</artifactId>
                        <version>3.6.2.2</version>
                    </dependency>-->
                    <!--自动生成@Table、@Id等注解-->
                    <dependency>
                        <groupId>tk.mybatis</groupId>
                        <artifactId>mapper</artifactId>
                        <version>4.0.0</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

二、application.yml配置

1. 新增配置

# 分页配置
pagehelper:
  # 分页插件会自动检测当前的数据库链接,自动选择合适的分页方式。你也可以配置helperDialect属性来指定分页插件使用哪种方言
  helper-dialect: mysql
  # 分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超
  # 过总数时),会查询最后一页。默认false 时,直接根据参数进行查询
  reasonable: true

# log日志
#mybatis:
#  configuration:
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level:
    com.feng.dao: debug

#swagger
swagger2:
  enable: true

2. 全配置

server:
  port: 8086
spring:
  application:
    name: company-frame
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://192.168.131.168:3306/CLASS?useUnicode=true&characterEncoding=utf-8&useSSL=false
      username: root
      password: Dataadt123!

mybatis:
  # 配置映射类所在的包名
  type-aliases-package: com.feng.bean, com.feng.vo.req, com.feng.vo.resp
  # 配置 mapper xml 文件所在的路径, 如果不配置 会报错:org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
  # 也就是 java 找不到 mapper 的 xml 文件中的语句
  mapper-locations: classpath:mapper/*.xml
  # mybatis 打印 SQL 语句
#  configuration:
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

pagehelper:
  # 分页插件会自动检测当前的数据库链接,自动选择合适的分页方式。你也可以配置helperDialect属性来指定分页插件使用哪种方言
  helper-dialect: mysql
  # 分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超
  # 过总数时),会查询最后一页。默认false 时,直接根据参数进行查询
  reasonable: true

# log日志
logging:
  level:
    com.feng.dao: debug

#swagger
swagger2:
  enable: true

3. 打印SQL日志配置(两种)

mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
logging:
  level:
    com.feng.dao: debug

这两个配置都可以
区别在于:
第一个是启用mybatis的SQL日志打印
第二个是启用springboot的日志框架。

四、统一的数据返回格式

1. 定义统一数据返回格式(important)

统一数据返回格式包括三个数据:

  • code:int类型,请求响应编码,0表示请求成功,其他表示失败
  • msg:String类型,响应客户端的提示
  • data:T 泛型,响应客户端内容

新建包 utils 存放DataResult.java
新建包 exception.code 存放ResponseCodeInterface.javaBaseResponseCode.java

DataResult.java 为统一数据返回格式的类
ResponseCodeInterface.java为返回数据的code和data的接口
BaseResponseCode.java 为返回数据的code和data的各种情况定义。

com/feng/utils/DataResult.java
com/feng/exception/code/ResponseCodeInterface.java
com/feng/exception/code/BaseResponseCode.java

2. DataResult.java

编写新包新类:utils/DataResult.java
其中内容如下:

package com.feng.utils;

import com.feng.exception.code.BaseResponseCode;
import com.feng.exception.code.ResponseCodeInterface;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@Data
public class DataResult<T> {
    /*
     * 请求响应code,0表示请求成功,其他表示失败
     * */
    @ApiModelProperty(value = "请求响应code,0表示请求成功,其他表示失败")
    private int code = 0;

    /*
     * 响应客户端的提示
     * */
    @ApiModelProperty(value = "响应异常码详细情况")
    private String msg;

    /*
     * 响应客户端内容
     * */
    @ApiModelProperty(value = "响应客户端内容")
    private T data;

    /*
    * 先编写 7个 构造函数,然后再编写静态函数,便于开发
    * */

    public DataResult() {
        this.code = BaseResponseCode.SUCCESS.getCode();
        this.msg = BaseResponseCode.SUCCESS.getMsg();
        this.data = null;
    }


    public DataResult(T data) {
        this.code = BaseResponseCode.SUCCESS.getCode();
        this.msg = BaseResponseCode.SUCCESS.getMsg();
        this.data = data;
    }

    public DataResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public DataResult(int code, T data) {
        this.code = code;
        this.msg = null;
        this.data = data;
    }

    public DataResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public DataResult(ResponseCodeInterface responseCodeInterface) {
        this.code = responseCodeInterface.getCode();
        this.msg = responseCodeInterface.getMsg();
        this.data = null;
    }

    public DataResult(ResponseCodeInterface responseCodeInterface, T data) {
        this.code = responseCodeInterface.getCode();
        this.msg = responseCodeInterface.getMsg();
        this.data = data;
    }


    // 以下 为定义的方法,直接调用上面封装好的 构造方法。  6个
    /**
     * 操作成功 data 不为null
     */
    public static <T> DataResult success(T data) {
        return new <T>DataResult(data);
    }

    /**
     * 操作成功 data为null
     */
    public static <T> DataResult success() {
        return new <T>DataResult();
    }

    /**
     * 自定义 返回操作 data 可控
     */
    public static <T> DataResult getResult(int code, String msg, T data) {
        return new <T>DataResult(code, msg, data);
    }

    /**
     * 自定义返回  data为null
     */
    public static <T> DataResult getResult(int code, String msg) {
        return new <T>DataResult(code, msg);
    }

    /**
     * 自定义返回 入参一般是异常code枚举 data为空
     */
    public static <T> DataResult getResult(BaseResponseCode responseCode) {
        return new <T>DataResult(responseCode);
    }

    /**
     * 自定义返回 入参一般是异常code枚举 data 可控
     */
    public static <T> DataResult getResult(BaseResponseCode responseCode, T data) {
        return new <T>DataResult(responseCode, data);
    }
}

4. ResponseCodeInterface.java 接口

package com.feng.exception.code;

/**
 * @ClassName: ResponseCodeInterface
 * TODO:类文件简单描述
 * @Author: 冯凡利
 * @UpdateUser: 冯凡利
 * @Version: 0.0.1
 */
public interface ResponseCodeInterface {
    int getCode();
    String getMsg();
}

3. BaseResponseCode.java枚举类

package com.feng.exception.code;

/**
 * @ClassName: BaseResponseCode
 * @Description: 响应码约定
 * @Author: 冯凡利
 * @UpdateUser: 冯凡利
 * @Version: 0.0.1
 */
public enum BaseResponseCode implements ResponseCodeInterface {
    /**
     * 这个要和前段约定好
     * code=0:服务器已成功处理了请求。 通常,这表示服务器提供了请求的网页。
     * code=4010001:(授权异常) 请求要求身份验证。 客户端需要跳转到登录页面重新登录
     * code=4010002:(凭证过期) 客户端请求 刷新凭证接口
     * code=4030001:没有权限禁止访问
     * code=400xxxx:系统主动抛出的业务异常
     * code=5000001:系统异常
     */
    SUCCESS(0, "操作成功"),
    SYSTEM_ERROR(5000001, "系统异常请稍后再试"),
    DATA_ERROR(4000001, "传入数据异常"),
    METHOD_IDENTITY_ERROR(4000002, "数据校验异常"),
    ACCOUNT_ERROR(4000003, "该账号不存在"),
    ACCOUNT_LOCK(4010001, "该账号被锁定,请联系系统管理员"),
    ACCOUNT_PASSWORD_ERROR(4000004, "用户名密码不匹配"),
    TOKEN_ERROR(4010001, "用户未登录,请重新登录"),
    TOKEN_NOT_NULL(4010001, "token 不能为空"),
    SHIRO_AUTHENTICATION_ERROR(4010001, "用户认证异常"),
    ACCOUNT_HAS_DELETED_ERROR(4010001, "该账号已被删除,请联系系统管理员"),
    TOKEN_PAST_DUE(4010002, "token失效,请刷新token"),
    NOT_PERMISSION(4030001, "没有权限访问该资源"),
    OPERATION_ERROR(4000005, "操作失败"),
    OPERATION_MENU_PERMISSION_CATALOG_ERROR(4000006, "操作后的菜单类型是目录,所属菜单必须为默认*菜单或者目录"),
    OPERATION_MENU_PERMISSION_MENU_ERROR(4000007, "操作后的菜单类型是菜单,所属菜单必须为目录类型"),
    OPERATION_MENU_PERMISSION_BTN_ERROR(4000008, "操作后的菜单类型是按钮,所属菜单必须为菜单类型"),
    OPERATION_MENU_PERMISSION_URL_NOT_NULL(4000009, "菜单权限的url不能为空"),
    OPERATION_MENU_PERMISSION_URL_PERMS_NULL(4000010, "菜单权限的标识符不能为空"),
    OPERATION_MENU_PERMISSION_URL_METHOD_NULL(4000011, "菜单权限的请求方式不能为空"),
    ACCOUNT_LOCK_TIP(4010012, "该账号被锁定,请联系系统管理员"),
    OPERATION_MENU_PERMISSION_UPDATE(4010013, "操作的菜单权限存在子集关联不允许变更"),
    ROLE_PERMISSION_RELATION(4010014, "该菜单权限存在子集关联,不允许删除"),
    NOT_PERMISSION_DELETED_DEPT(4010015, "该组织机构下还关联着用户,不允许删除"),
    OLD_PASSWORD_ERROR(4010016, "旧密码不匹配"),
    OPERATION_MENU_PERMISSION_URL_CODE_NULL(4000011, "菜单权限的按钮标识不能为空"),
    ;

    /**
     * 响应码
     */
    private int code;
    /**
     * 提示
     */
    private String msg;

    BaseResponseCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    @Override
    public int getCode() {
        return code;
    }

    @Override
    public String getMsg() {
        return msg;
    }
}

五、请求模块

编写vo包,此包下,新建 reqresp包,即:com/feng/vo/reqcom/feng/vo/resp

req包,存放请求的数据。
resp包,存放响应的数据。

1. vo/req/StudentPageReqVo.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class StudentPageReqVo implements Serializable {

    @ApiModelProperty(value = "当前第几页")
    private Integer pageNum = 1;

    @ApiModelProperty(value = "当前页数量")
    private Integer pageSize = 10;
}

2. vo/resp/PageRespVo.java

/**
 * @ClassName: PageVO
 * @Description: 分页 POJO 返回的响应数据
 * @createTime: 2020/2/5 15:45
 * @Author: 冯凡利
 * @UpdateUser: 冯凡利
 * @Version: 0.0.1
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageRespVo<T> implements Serializable {
    /**
     * 总 记录数
     */
    @ApiModelProperty(value = "总记录数")
    private Long totalRows;

    /**
     * 总 页数
     */
    @ApiModelProperty(value = "总页数")
    private Integer totalPages;

    /**
     * 当前 第几页
     */
    @ApiModelProperty(value = "当前第几页")
    private Integer nowPageNum;
    /**
     * 每页 记录数
     */
    @ApiModelProperty(value = "每页记录数")
    private Integer pageSize;
    /**
     * 当前页 记录数
     */
    @ApiModelProperty(value = "当前页记录数")
    private Integer curPageSize;
    /**
     * 数据 列表
     */
    @ApiModelProperty(value = "数据列表")
    private List<T> dataList;
}

六、utils工具模块

1. 定义

utils包存放各种工具类,比如分页工具类,统一数据返回格式类等等。
在utils包中编写分页工具类PageUtil.java
会在业务层用到。

1. 分页工具类:PageUtil.java(important)

package com.feng.utils;

import com.feng.vo.resp.PageRespVo;
import com.github.pagehelper.Page;

import java.util.List;

public class PageUtil {
    public PageUtil() {
    }

    public static <T> PageRespVo<T> getPageVO(List<T> list){
        PageRespVo<T> respVo = new PageRespVo<>();

        if (list instanceof Page) {
            Page page = (Page) list; // 将结果集 list 强转为 page 对象,则
            respVo.setTotalRows(page.getTotal()); // 总记录数
            respVo.setTotalPages(page.getPages());
            respVo.setNowPageNum(page.getPageNum());// 当前页数
            respVo.setCurPageSize(page.getPageSize());// 当前页 记录数
            respVo.setPageSize(page.size()); // 每页 记录数
            respVo.setDataList(page.getResult()); // 数据 列表
        }

        return respVo;
    }
}

七、业务代码

1. bean模型层

Student.java

package com.feng.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable {
    private Integer stuId;

    private String name;

    private String gender;

    private Integer age;

    private String nation;

    private static final long serialVersionUID = 1L;

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", stuId=").append(stuId);
        sb.append(", name=").append(name);
        sb.append(", gender=").append(gender);
        sb.append(", age=").append(age);
        sb.append(", nation=").append(nation);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

2. controller控制层

package com.feng.controller;

import com.feng.bean.Student;
import com.feng.service.StudentService;
import com.feng.utils.DataResult;
import com.feng.vo.req.StudentPageReqVo;
import com.feng.vo.resp.PageRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/stu/{userId}")
    public DataResult<Student> getStuByIdPath(@PathVariable Integer userId){
        Student student = studentService.getStuById(userId);
        DataResult result = DataResult.success(student);
        return result;
    }

    @GetMapping(value = "/stu")
    @ResponseBody
    public DataResult<Student> getCompanyByIdGET(@RequestParam(value = "userId") Integer id) {
        Student student = studentService.getStuById(id);
        DataResult result = DataResult.success(student);
        return result;
    }

    @PostMapping(value = "/stuPageInfo")
    @ResponseBody
    public DataResult<PageRespVo<Student>> getStuPageInfo(@RequestBody StudentPageReqVo studentPageReqVo){
        PageRespVo<Student> stuPageInfo = studentService.getStuPageInfo(studentPageReqVo);
        DataResult result = DataResult.success(stuPageInfo);
        return result;
    }

    @GetMapping(value = "/allStu")
    @ResponseBody
    public DataResult<List<Student>> getAllStu(){
        List<Student> students = studentService.getAllStu();
        DataResult result = DataResult.success(students);
        return result;
    }
}

3. service业务层

a. StudentService 接口

package com.feng.service;

import com.feng.bean.Student;
import com.feng.vo.req.StudentPageReqVo;
import com.feng.vo.resp.PageRespVo;

import java.util.List;


public interface StudentService {

    Student getStuById(Integer userId);

    PageRespVo<Student> getStuPageInfo(StudentPageReqVo studentPageReqVo);

    List<Student> getAllStu();
}

b. StudentServiceImpl 实现类(分页二行语句)

impl包下的StudentServiceImpl.java 实现类

package com.feng.service.impl;

import com.feng.bean.Student;
import com.feng.dao.StudentMapper;
import com.feng.service.StudentService;
import com.feng.utils.PageUtil;
import com.feng.vo.req.StudentPageReqVo;
import com.feng.vo.resp.PageRespVo;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    public Student getStuById(Integer userId) {
        return studentMapper.selectByPrimaryKey(userId);
    }


    @Override
    public PageRespVo<Student> getStuPageInfo(StudentPageReqVo studentPageReqVo) {
        PageHelper.startPage(studentPageReqVo.getPageNum(), studentPageReqVo.getPageSize());
        List<Student> students = studentMapper.getAllStudent();
        return PageUtil.getPageVO(students);
    }

    @Override
    public List<Student> getAllStu() {
        return studentMapper.getAllStudent();
    }
}

4. dao数据层

目前只有getAllStudent()是我写的其余都是mybatis-generator自动生成的。


package com.feng.dao;

import com.feng.bean.Student;
import com.feng.vo.req.StudentPageReqVo;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface StudentMapper {
    int deleteByPrimaryKey(Integer stuId);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer stuId);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);

    List<Student> getAllStudent();
}

5. mapper SQL语句

其余的我就不在复制了,都是mybatis-generator逆向生成的,都在GitHub中可以查看

<select id="getAllStudent" resultType="com.feng.bean.Student">
  SELECT stu_id AS stuId, name, gender, age, nation
  FROM STUDENT
</select>

八、整合Swagger配置

1. Swagger2config.java

编写包 config,新建类 Swagger2config.java

package com.feng.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

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

@Configuration
public class Swagger2Config {
    /**
     * 引入 yml 配置文件中的自定义属性
     * 用来控制 swagger2 接口文档的开关,因为在生产环境中,是要关闭掉 swagger2 接口文档的
     */
    @Value("${swagger2.enable}")
    private boolean enable;

    @Bean
    public Docket createRestApi() {
        /*
         * 这是为了我们在用 swagger 测试接口的时候添加头部信息
         * 模拟使用 header 参数,非必填
         * */
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder tokenPar = new ParameterBuilder();
        ParameterBuilder refreshTokenPar = new ParameterBuilder();

        tokenPar.name("authorization").description("swagger测试用(模拟authorization传入)非必填 header").modelRef(new ModelRef("string")).parameterType("header").required(false);
        refreshTokenPar.name("refresh_token").description("swagger测试用(模拟刷新token传入)非必填 header").modelRef(new ModelRef("string")).parameterType("header").required(false);
        /**
         * 多个的时候 就直接添加到 pars 就可以了
         */
        pars.add(tokenPar.build());
        pars.add(refreshTokenPar.build());

        return new Docket(DocumentationType.SWAGGER_2)
                // 自定义的 描述表头信息
                .apiInfo(apiInfo())
                // 函数返回一个ApiSerlectorBuilder 实例来控制哪些接口暴露给 Swagger ui 来展示
                .select()
                // 指定需要扫描的包路径
                .apis(RequestHandlerSelectors.basePackage("com.feng.controller"))
                .paths(PathSelectors.any())
                .build()
                // 添加请求头等信息
                .globalOperationParameters(pars)
                // 设置swagger文档的开关
                .enable(enable);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot-mybatis")
                .description("springboot 整合 mybatis 实战系列")
                .termsOfServiceUrl("")
                .version("1.0")
                .build();
    }
}

2. 启动类开启

开启Swagger配置,需要在主类上启动,使用 @EnableSwagger2 注解即可。

//@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@MapperScan(value = {"com.feng.dao"})
@SpringBootApplication
@EnableSwagger2
public class SpringbootMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }

}

九、postman调用

1. 请求/allStu

GET http://localhost:8086/allStu
springboot整合mybatis使用三:使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块

2. 分页请求/stuPageInfo

POST http://localhost:8086/stuPageInfo
请求头:Content-Type: application/json
请求体raw中的JSON:

{
    "pageNum":2,
    "pageSize":2
}

springboot整合mybatis使用三:使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块

3. swagger2 UI展示

http://localhost:8086/swagger-ui.html#/
springboot整合mybatis使用三:使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块

本文地址:https://blog.csdn.net/qq_40036754/article/details/110491573