Spring Boot整合Mybatis Plus和Swagger2的教程详解

2025-05-29 0 51

前言:如果你是初学者,请完全按照我的教程以及代码来搭建(文末会附上完整的项目代码包,你可以直接下载我提供的完整项目代码包然后自行体验!),为了照顾初学者所以贴图比较多,请耐心跟着教程来,希望这个项目Demo能给你一些帮助,如果觉得写的还可以请给个关注和点赞,谢谢!

题外话:这是我第一篇用markdown来写的博文,格式不好的地方请见谅

一、pom.xml和application.yml

1、pom.xml中添加相关依赖,这里我把我的pom.xml代码贴出来

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.4.3</version>
  9. <relativePath/> <!– lookup parent from repository –>
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>study</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>study</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <!–依赖的版本–>
  18. <java.version>1.8</java.version>
  19. <mysql.version>8.0.13</mysql.version>
  20. <mybatisPlus.version>3.4.1</mybatisPlus.version>
  21. <druid.version>1.0.9</druid.version>
  22. <swagger.version>2.9.2</swagger.version>
  23. <hutool.version>5.5.8</hutool.version>
  24. </properties>
  25. <dependencies>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-web</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.projectlombok</groupId>
  32. <artifactId>lombok</artifactId>
  33. <optional>true</optional>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-starter-test</artifactId>
  38. <scope>test</scope>
  39. </dependency>
  40. <!–mysql–>
  41. <dependency>
  42. <groupId>mysql</groupId>
  43. <artifactId>mysql-connector-java</artifactId>
  44. <scope>runtime</scope>
  45. <version>${mysql.version}</version>
  46. </dependency>
  47. <!– MyBatis-Plus–>
  48. <dependency>
  49. <groupId>com.baomidou</groupId>
  50. <artifactId>mybatis-plus-boot-starter</artifactId>
  51. <version>${mybatisPlus.version}</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>com.baomidou</groupId>
  55. <artifactId>mybatis-plus-generator</artifactId>
  56. <version>${mybatisPlus.version}</version>
  57. </dependency>
  58. <!–druid–>
  59. <dependency>
  60. <groupId>com.alibaba</groupId>
  61. <artifactId>druid</artifactId>
  62. <version>${druid.version}</version>
  63. </dependency>
  64. <!–swagger2–>
  65. <dependency>
  66. <groupId>io.springfox</groupId>
  67. <artifactId>springfox-swagger2</artifactId>
  68. <version>${swagger.version}</version>
  69. </dependency>
  70. <dependency>
  71. <groupId>io.springfox</groupId>
  72. <artifactId>springfox-swagger-ui</artifactId>
  73. <version>${swagger.version}</version>
  74. </dependency>
  75. <!–hutool–>
  76. <dependency>
  77. <groupId>cn.hutool</groupId>
  78. <artifactId>hutool-all</artifactId>
  79. <version>${hutool.version}</version>
  80. </dependency>
  81. </dependencies>
  82. <build>
  83. <plugins>
  84. <plugin>
  85. <groupId>org.springframework.boot</groupId>
  86. <artifactId>spring-boot-maven-plugin</artifactId>
  87. <configuration>
  88. <excludes>
  89. <exclude>
  90. <groupId>org.projectlombok</groupId>
  91. <artifactId>lombok</artifactId>
  92. </exclude>
  93. </excludes>
  94. </configuration>
  95. </plugin>
  96. </plugins>
  97. </build>

2、在resources下新建application.yml文件,并添加如下配置

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. # 配置端口
  2. server:
  3. port: 8080
  4. #—————-druid数据源配置———————–
  5. spring:
  6. datasource:
  7. type: com.alibaba.druid.pool.DruidDataSource
  8. druid:
  9. #这里跟pom里面mysql-connector版本相关8.0之后用com.mysql.cj.jdbc.Driver,之前用com.mysql.jdbc.Driver
  10. driverclassname: com.mysql.cj.jdbc.Driver
  11. #这里改成你自己的数据库名称以及账号和密码
  12. url: jdbc:mysql://127.0.0.1:3306/study?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
  13. username: root
  14. password: 123456
  15. initialSize: 10
  16. minIdle: 10
  17. maxActive: 30
  18. # 配置获取连接等待超时的时间
  19. maxWait: 60000
  20. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  21. timeBetweenEvictionRunsMillis: 60000
  22. # 配置一个连接在池中最小生存的时间,单位是毫秒
  23. minEvictableIdleTimeMillis: 300000
  24. validationQuery: SELECT 1 FROM DUAL
  25. testWhileIdle: true
  26. testOnBorrow: false
  27. testOnReturn: false
  28. # 打开PSCache,并且指定每个连接上PSCache的大小
  29. poolPreparedStatements: true
  30. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  31. #filters: stat,wall,log4j
  32. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  33. connectionproperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  34. # 合并多个DruidDataSource的监控数据
  35. useGlobalDataSourceStat: true
  36. #—————-mybatis plus配置———————–
  37. mybatisplus:
  38. # xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置)
  39. mapperlocations: classpath:mapper/*.xml
  40. configuration:
  41. # 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
  42. map-underscore-to-camel-case: true
  43. # 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,不会映射这个字段
  44. call-setters-on-nulls: true
  45. # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
  46. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  47. # 实体扫描,多个package用逗号或者分号分隔(这里更改为你的实体类存放路径)
  48. typeAliasesPackage: com.example.study.model.entity
  49. global-config:
  50. db-config:
  51. #主键类型 AUTO:"数据库ID自增" INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
  52. id-type: auto
  53. #字段策略 IGNORED:"忽略判断" NOT_NULL:"非 NULL 判断") NOT_EMPTY:"非空判断"
  54. field-strategy: NOT_EMPTY
  55. #数据库类型
  56. db-type: MYSQL
  57. # 逻辑删除配置
  58. # 删除前
  59. logic-not-delete-value: 1
  60. # 删除后
  61. logic-delete-value: 0
  62. #—————-swagger配置———————–
  63. swagger:
  64. #生产环境改为false(改为false后swagger-ui.html则无法访问)
  65. enable: true
  66. #解决Swagger2 异常 NumberFormatException:For input string:""
  67. logging:
  68. level:
  69. io:
  70. swagger:
  71. models:
  72. parameters:
  73. AbstractSerializableParameter: ERROR

二、整合Swagger2

1、添加swagger的配置类SwaggerConfig.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.config;
  2. import io.swagger.annotations.Api;
  3. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import springfox.documentation.builders.ApiInfoBuilder;
  7. import springfox.documentation.builders.PathSelectors;
  8. import springfox.documentation.builders.RequestHandlerSelectors;
  9. import springfox.documentation.service.ApiInfo;
  10. import springfox.documentation.service.ApiKey;
  11. import springfox.documentation.spi.DocumentationType;
  12. import springfox.documentation.spring.web.plugins.Docket;
  13. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. /**
  17. * Swagger配置类
  18. *
  19. * @author 154594742@qq.com
  20. * @date: 2021/2/22 10:02:00
  21. */
  22. @Configuration
  23. @EnableSwagger2
  24. @ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
  25. public class SwaggerConfig {
  26. /**
  27. * 创建API应用
  28. * apiInfo() 增加API相关信息
  29. * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
  30. * 本例采用指定扫描的包路径来定义指定要建立API的目录。
  31. *
  32. * @return
  33. */
  34. @Bean
  35. public Docket createRestApi() {
  36. return new Docket(DocumentationType.SWAGGER_2)
  37. .apiInfo(this.apiInfo())
  38. .select()
  39. //设置选择器,选择带Api接口类的类
  40. .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
  41. //api包扫描
  42. .apis(RequestHandlerSelectors.basePackage("com.example.study"))
  43. .paths(PathSelectors.any())
  44. .build()
  45. .securitySchemes(securitySchemes());
  46. }
  47. /**
  48. * 创建该API的基本信息(这些基本信息会展现在文档页面中)
  49. * 访问地址:http://ip:端口/swagger-ui.html
  50. *
  51. * @return ApiInfo
  52. */
  53. private ApiInfo apiInfo() {
  54. return new ApiInfoBuilder().title("demo项目")
  55. .description("demo项目API文档")
  56. .termsOfServiceUrl("http://localhost")
  57. .version("1.0")
  58. .build();
  59. }
  60. private List<ApiKey> securitySchemes() {
  61. List<ApiKey> apiKeyList= new ArrayList<>();
  62. //apiKeyList.add(new ApiKey("token", "令牌", "header"));
  63. return apiKeyList;
  64. }
  65. }

2、新建controller包并且在controller包下新建IndexController.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.controller;
  2. import io.swagger.annotations.Api;
  3. import io.swagger.annotations.ApiOperation;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. /**
  9. * 首页控制器
  10. * @author 154594742@qq.com
  11. * @date: 2021/2/22 10:02:00
  12. */
  13. @Api(tags = "首页控制器")
  14. @RestController
  15. public class IndexController {
  16. @ApiOperation("首页html")
  17. @GetMapping("/")
  18. public String index(){
  19. return "hello index";
  20. }
  21. }

3、启动StudyApplication.java后访问http://localhost:8080/swagger-ui.html,出现第二图所示则表示swagger整合完成

Spring Boot整合Mybatis Plus和Swagger2的教程详解
Spring Boot整合Mybatis Plus和Swagger2的教程详解

三、整合Mybatis Plus

1、如图创建MybatisPlusConfi.java配置分页插件

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.config;
  2. import com.baomidou.mybatisplus.annotation.DbType;
  3. import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
  4. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
  5. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
  6. import org.mybatis.spring.annotation.MapperScan;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. /**
  10. * 配置MybatisPlus分页插件
  11. *
  12. * @author 154594742@qq.com
  13. * @date: 2021/2/22 10:02:00
  14. */
  15. @Configuration
  16. @MapperScan("com.example.study.mapper")
  17. public class MybatisPlusConfig {
  18. /**
  19. * Mybatis-plus3.4.0版本过后使用MybatisPlusInterceptor分页插件
  20. * 注意:DbType.MYSQL必须为自己使用的数据库类型,否则分页不生效
  21. */
  22. @Bean
  23. public MybatisPlusInterceptor mybatisPlusInterceptor() {
  24. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  25. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
  26. return interceptor;
  27. }
  28. /**
  29. * 设置useDeprecatedExecutor = false 避免缓存出现问题
  30. * @return
  31. */
  32. @Bean
  33. public ConfigurationCustomizer configurationCustomizer() {
  34. return configuration -> configuration.setUseDeprecatedExecutor(false);
  35. }
  36. }

2、在数据库中创建测试表

  1. CREATE TABLE `t_user` (
  2. `id` bigint NOT NULL AUTO_INCREMENT,
  3. `name` varchar(32) DEFAULT NULL,
  4. `age` int DEFAULT NULL,
  5. PRIMARY KEY (`id`)
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8

3、创建实体类UserEntity.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.model.entity;
  2. import com.baomidou.mybatisplus.annotation.IdType;
  3. import com.baomidou.mybatisplus.annotation.TableField;
  4. import com.baomidou.mybatisplus.annotation.TableId;
  5. import com.baomidou.mybatisplus.annotation.TableName;
  6. import io.swagger.annotations.ApiModel;
  7. import io.swagger.annotations.ApiModelProperty;
  8. import lombok.AllArgsConstructor;
  9. import lombok.Data;
  10. import lombok.NoArgsConstructor;
  11. import java.io.Serializable;
  12. /**
  13. * 用户信息实体类
  14. *
  15. * @author 154594742@qq.com
  16. * @date: 2021/2/22 10:02:00
  17. */
  18. @Data
  19. @NoArgsConstructor
  20. @AllArgsConstructor
  21. @ApiModel(value = "UserEntity", description = "用户实体")
  22. @TableName("t_user")
  23. public class UserEntity implements Serializable {
  24. private static final long serialVersionUID = 6928834261563057243L;
  25. /**
  26. * 唯一标识,自增主键
  27. */
  28. @ApiModelProperty(value = "id")
  29. @TableId(value = "id", type = IdType.AUTO)
  30. private Long id;
  31. /**
  32. * 姓名
  33. */
  34. @ApiModelProperty(value = "姓名")
  35. @TableField("name")
  36. private String name;
  37. /**
  38. * 年龄
  39. */
  40. @ApiModelProperty(value = "年龄")
  41. @TableField("age")
  42. private Integer age;
  43. }

4、创建UserMapper.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.example.study.model.entity.UserEntity;
  4. /**
  5. * @author 154594742@qq.com
  6. */
  7. public interface UserMapper extends BaseMapper<UserEntity> {
  8. }

5、创建UserService.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.service;
  2. import com.baomidou.mybatisplus.extension.service.IService;
  3. import com.example.study.model.entity.UserEntity;
  4. /**
  5. * @author 154594742@qq.com
  6. */
  7. public interface UserService extends IService<UserEntity> {
  8. }

6、创建UserServiceImpl.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.service.impl;
  2. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  3. import com.example.study.model.entity.UserEntity;
  4. import com.example.study.mapper.UserMapper;
  5. import com.example.study.service.UserService;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * @author 154594742@qq.com
  9. */
  10. @Service
  11. public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
  12. }

7、创建UserController.java(这里编译器会提示一些错误暂时不用管,因为缺少一些类的代码)

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.controller;
  2. import com.baomidou.mybatisplus.core.metadata.IPage;
  3. import com.example.study.model.entity.UserEntity;
  4. import com.example.study.model.param.UserParam;
  5. import com.example.study.model.vo.ResponseVo;
  6. import com.example.study.service.UserService;
  7. import com.example.study.util.CommonQueryPageUtils;
  8. import com.example.study.util.BuildResponseUtils;
  9. import io.swagger.annotations.Api;
  10. import io.swagger.annotations.ApiOperation;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.web.bind.annotation.*;
  13. /**
  14. * 用户控制器
  15. *
  16. * @author 154594742@qq.com
  17. * @date: 2021/2/22 10:02:00
  18. */
  19. @RestController
  20. @Api(tags = "用户控制器")
  21. public class UserController {
  22. @Autowired
  23. private UserService userService;
  24. @ApiOperation("新增")
  25. @PostMapping("user")
  26. public ResponseVo<?> add(UserEntity entity) {
  27. return userService.save(entity) ? BuildResponseUtils.success() : BuildResponseUtils.error();
  28. }
  29. @ApiOperation("通过id查询")
  30. @GetMapping("user/{id}")
  31. public ResponseVo<UserEntity> getById(@PathVariable String id) {
  32. return BuildResponseUtils.buildResponse(userService.getById(id));
  33. }
  34. @ApiOperation("修改")
  35. @PutMapping("user")
  36. public ResponseVo<?> update(UserEntity entity) {
  37. return userService.updateById(entity) ? BuildResponseUtils.success() : BuildResponseUtils.error();
  38. }
  39. @ApiOperation("通过id删除")
  40. @DeleteMapping("user/{id}")
  41. public ResponseVo<?> delete(@PathVariable String id) {
  42. return userService.removeById(id) ? BuildResponseUtils.success() : BuildResponseUtils.error();
  43. }
  44. @ApiOperation("分页查询")
  45. @GetMapping("userPage")
  46. public ResponseVo<IPage<UserEntity>> selectPage(UserParam param) {
  47. return BuildResponseUtils.buildResponse(CommonQueryPageUtils.commonQueryPage(param, userService));
  48. }
  49. }

8、创建枚举CodeMsgEnum.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.enums;
  2. /**
  3. * 异常类code常量(code值不要重复)
  4. *
  5. * @author 154594742@qq.com
  6. * @date: 2021/2/22 9:42:00
  7. */
  8. public enum CodeMsgEnum {
  9. //请求成功
  10. SUCCESS("0","成功!"),
  11. //系统异常
  12. FAIL("1","失败!"),
  13. //以下是业务异常
  14. LOGIN_NO_PASS("1001","用户名或密码错误"),
  15. ;
  16. /**
  17. * 状态码
  18. */
  19. public String code;
  20. /**
  21. * 状态码对应信息
  22. */
  23. public String msg;
  24. CodeMsgEnum(String code, String msg) {
  25. this.code = code;
  26. this.msg = msg;
  27. }
  28. }

9、创建统一的返回结果类ResponseVo.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.model.vo;
  2. import io.swagger.annotations.ApiModel;
  3. import io.swagger.annotations.ApiModelProperty;
  4. import lombok.AllArgsConstructor;
  5. import lombok.Data;
  6. import lombok.NoArgsConstructor;
  7. import java.io.Serializable;
  8. /**
  9. * 统一的返回对象VO
  10. *
  11. * @author 154594742@qq.com
  12. * @date: 2021/2/22 10:02:00
  13. */
  14. @Data
  15. @NoArgsConstructor
  16. @AllArgsConstructor
  17. @ApiModel(value = "ResponseVo", description = "统一的返回对象")
  18. public class ResponseVo<T> implements Serializable {
  19. private static final long serialVersionUID = 7748070653645596712L;
  20. /**
  21. * 状态码
  22. */
  23. @ApiModelProperty(value = "状态码")
  24. private String code;
  25. /**
  26. * 状态码对应描述信息
  27. */
  28. @ApiModelProperty(value = "状态码对应描述信息")
  29. private String msg;
  30. /**
  31. * 数据
  32. */
  33. @ApiModelProperty(value = "数据")
  34. private T data;
  35. }

10、创建常量类QueryMethodConstant.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.constant;
  2. /**
  3. * mybatis plus常用的查询方式
  4. * @author 154594742@qq.com
  5. * @date 2021/2/23 11:24
  6. */
  7. public interface QueryMethodConstant {
  8. /**
  9. * 相同
  10. */
  11. String EQ = "EQ";
  12. /**
  13. * 不相同
  14. */
  15. String NE = "NE";
  16. /**
  17. * 相似,左右模糊(like '%值%')
  18. */
  19. String LIKE = "LIKE";
  20. /**
  21. * 相似,左模糊(like '%值')
  22. */
  23. String LIKE_LIFT = "LIKE_LIFT";
  24. /**
  25. * 相似,右模糊(like '值%')
  26. */
  27. String LIKE_RIGHT = "LIKE_RIGHT";
  28. /**
  29. * 不相似 (not like '%值%')
  30. */
  31. String NOT_LIKE = "NOT_LIKE";
  32. /**
  33. * 大于
  34. */
  35. String GT = "GT";
  36. /**
  37. * 大于等于
  38. */
  39. String GE = "GE";
  40. /**
  41. * 小于
  42. */
  43. String LT = "LT";
  44. /**
  45. * 小于等于
  46. */
  47. String LE = "LE";
  48. }

11、创建自定义注解QueryMethod.java(用于后续的通用分页查询工具类)

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.annotation;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7. * 查询方式的自定义注解
  8. * @author 154594742@qq.com
  9. * @date 2021/2/23 11:24
  10. */
  11. @Retention(RetentionPolicy.RUNTIME)
  12. @Target(value = ElementType.FIELD)
  13. public @interface QueryMethod {
  14. /**
  15. * 字段名
  16. */
  17. String field() default "";
  18. /**
  19. * 匹配方式
  20. */
  21. String method() default "";
  22. }

12、创建构建返回结果工具类BuildResponseUtils.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.util;
  2. import com.example.study.enums.CodeMsgEnum;
  3. import com.example.study.model.vo.ResponseVo;
  4. /**
  5. * 构建返回结果工具类
  6. *
  7. * @author 154594742@qq.com
  8. * @date: 2021/2/22 10:02:00
  9. */
  10. public final class BuildResponseUtils {
  11. /**
  12. * 构建正确请求的response
  13. *
  14. * @return ResponseVo 统一的返回结果
  15. */
  16. public static ResponseVo<?> success() {
  17. ResponseVo<?> response = new ResponseVo<>();
  18. response.setCode(CodeMsgEnum.SUCCESS.code);
  19. response.setMsg(CodeMsgEnum.SUCCESS.msg);
  20. return response;
  21. }
  22. /**
  23. * 构建业务异常的response
  24. * @param codeMsgEnum 枚举
  25. * @return ResponseVo 统一的返回结果
  26. */
  27. public static ResponseVo<?> success(CodeMsgEnum codeMsgEnum) {
  28. ResponseVo<?> response = new ResponseVo<>();
  29. response.setCode(codeMsgEnum.code);
  30. response.setMsg(codeMsgEnum.msg);
  31. return response;
  32. }
  33. /**
  34. * 构建自定义code和msg的业务异常
  35. *
  36. * @param code 自定义code
  37. * @param msg 自定义msg
  38. * @return ResponseVo 统一的返回结果
  39. */
  40. public static ResponseVo<?> success(String code, String msg) {
  41. ResponseVo<?> response = new ResponseVo<>();
  42. response.setCode(code);
  43. response.setMsg(msg);
  44. return response;
  45. }
  46. /**
  47. * 构建系统异常的response(只用于系统异常)
  48. * @return ResponseVo 统一的返回结果
  49. */
  50. public static ResponseVo<?> error() {
  51. ResponseVo<?> response = new ResponseVo<>();
  52. response.setCode(CodeMsgEnum.FAIL.code);
  53. response.setMsg(CodeMsgEnum.FAIL.msg);
  54. return response;
  55. }
  56. /**
  57. * 构建返回结果
  58. * @param obj 结果数据
  59. * @param <T> 结果数据的泛型
  60. * @return ResponseVo 统一的返回结果
  61. */
  62. public static <T> ResponseVo<T> buildResponse(T obj) {
  63. ResponseVo<T> response = new ResponseVo<>();
  64. response.setData(obj);
  65. response.setCode(CodeMsgEnum.SUCCESS.code);
  66. response.setMsg(CodeMsgEnum.SUCCESS.msg);
  67. return response;
  68. }
  69. }

13、创建分页查询工具类CommonQueryPageUtils.java(本人自己封装的,功能可能不是很完善,但是基本的单表查询够用了)

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.util;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.baomidou.mybatisplus.core.metadata.IPage;
  4. import com.baomidou.mybatisplus.core.metadata.OrderItem;
  5. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  6. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  7. import com.baomidou.mybatisplus.extension.service.IService;
  8. import com.example.study.annotation.QueryMethod;
  9. import com.example.study.constant.QueryMethodConstant;
  10. import com.example.study.model.param.PageParam;
  11. import java.lang.reflect.Field;
  12. import java.util.Locale;
  13. /**
  14. * 分页查询工具类
  15. *
  16. * @author 154594742@qq.com
  17. * @date: 2021/2/22 10:02:00
  18. */
  19. public final class CommonQueryPageUtils {
  20. /**
  21. * 正序
  22. */
  23. private static final String ASC = "asc";
  24. /**
  25. * 倒序
  26. */
  27. private static final String DESC = "desc";
  28. /**
  29. * 通用的带排序功能的分页查询
  30. */
  31. public static <T> IPage<T> commonQueryPage(PageParam param, IService<T> service) {
  32. //构建page
  33. //根据传入的排序设置order
  34. //排序字段(格式:字段名:排序方式,字段名:排序方式 (asc正序,desc倒序) 示例:id:desc,age:asc)
  35. Page<T> page = new Page<>(param.getPage(), param.getLimit());
  36. String orders = param.getOrders();
  37. if (StringUtils.isNotBlank(orders)) {
  38. String[] splitArr = orders.split(",");
  39. for (String str : splitArr) {
  40. if (StringUtils.isBlank(str)) {
  41. continue;
  42. }
  43. String[] strArr = str.split(":");
  44. if (strArr.length != 2 || StringUtils.isBlank(strArr[0]) || StringUtils.isBlank(strArr[1])) {
  45. continue;
  46. }
  47. if (ASC.equals(strArr[1].toLowerCase(Locale.ROOT))) {
  48. page.addOrder(OrderItem.asc(strArr[0]));
  49. continue;
  50. }
  51. if (DESC.equals(strArr[1].toLowerCase(Locale.ROOT))) {
  52. page.addOrder(OrderItem.desc(strArr[0]));
  53. }
  54. }
  55. }
  56. //根据自定义注解构建queryWrapper
  57. QueryWrapper<T> queryWrapper = new QueryWrapper<>();
  58. Class<? extends PageParam> clazz = param.getClass();
  59. Field[] fields = clazz.getDeclaredFields();
  60. for (Field field : fields) {
  61. //设置对象的访问权限,保证对private的属性可以访问
  62. field.setAccessible(true);
  63. QueryMethod annotation = field.getAnnotation(QueryMethod.class);
  64. try {
  65. //属性没有值则跳过
  66. if (null == field.get(param)) {
  67. continue;
  68. }
  69. //没有加@QueryMethod 默认属性名为字段名,默认匹配方式为eq
  70. if (null == annotation) {
  71. queryWrapper.eq(field.getName(), field.get(param));
  72. continue;
  73. }
  74. switch (annotation.method()) {
  75. case QueryMethodConstant.EQ:
  76. queryWrapper.eq(annotation.field(), field.get(param));
  77. break;
  78. case QueryMethodConstant.NE:
  79. queryWrapper.ne(annotation.field(), field.get(param));
  80. break;
  81. case QueryMethodConstant.LIKE:
  82. queryWrapper.like(annotation.field(), field.get(param));
  83. break;
  84. case QueryMethodConstant.LIKE_LIFT:
  85. queryWrapper.likeLeft(annotation.field(), field.get(param));
  86. break;
  87. case QueryMethodConstant.LIKE_RIGHT:
  88. queryWrapper.likeRight(annotation.field(), field.get(param));
  89. break;
  90. case QueryMethodConstant.GT:
  91. queryWrapper.gt(annotation.field(), field.get(param));
  92. break;
  93. case QueryMethodConstant.GE:
  94. queryWrapper.ge(annotation.field(), field.get(param));
  95. break;
  96. case QueryMethodConstant.LT:
  97. queryWrapper.lt(annotation.field(), field.get(param));
  98. break;
  99. case QueryMethodConstant.LE:
  100. queryWrapper.le(annotation.field(), field.get(param));
  101. break;
  102. default:
  103. ;
  104. }
  105. } catch (IllegalAccessException e) {
  106. e.printStackTrace();
  107. }
  108. }
  109. return service.page(page, queryWrapper);
  110. }
  111. }

14、创建统一的分页查询请求参数类PageParam.java

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.model.param;
  2. import io.swagger.annotations.ApiModel;
  3. import io.swagger.annotations.ApiModelProperty;
  4. import lombok.Data;
  5. import java.util.LinkedHashMap;
  6. /**
  7. * 统一的分页查询请求参数
  8. *
  9. * @author 154594742@qq.com
  10. * @date 2021/2/22 17:24
  11. */
  12. @Data
  13. @ApiModel(value = "PageParam", description = "分页参数")
  14. public class PageParam {
  15. /**
  16. * 页码
  17. */
  18. @ApiModelProperty(value = "页码,不传则默认1")
  19. private Integer page = 1;
  20. /**
  21. * 每页条数
  22. */
  23. @ApiModelProperty(value = "每页条数,不传则默认10")
  24. private Integer limit = 10;
  25. /**
  26. * 排序字段(格式:字段名:排序方式,字段名:排序方式 (asc正序,desc倒序) 示例:id:desc,age:asc)
  27. */
  28. @ApiModelProperty(value = "排序字段(格式:字段名:排序方式,字段名:排序方式 (asc正序,desc倒序) 示例:id:desc,age:asc)")
  29. private String orders;
  30. }

15、创建用户查询条件类UserParam.java继承PageParam(以后分页查询的参数类都要继承PageParam)

Spring Boot整合Mybatis Plus和Swagger2的教程详解

  1. package com.example.study.model.param;
  2. import com.example.study.annotation.QueryMethod;
  3. import com.example.study.constant.QueryMethodConstant;
  4. import io.swagger.annotations.ApiModel;
  5. import io.swagger.annotations.ApiModelProperty;
  6. import lombok.Data;
  7. /**
  8. * 用户查询条件类(需要根据哪些字段查询就添加哪些字段)
  9. * @author 154594742@qq.com
  10. * @date 2021/2/22 17:24
  11. */
  12. @Data
  13. @ApiModel(value = "UserParam", description = "用户查询条件")
  14. public class UserParam extends PageParam {
  15. /**
  16. * 通过@QueryMethod注解来控制匹配的方式,这里查询条件为 name like ‘%值%'
  17. */
  18. @ApiModelProperty(value = "姓名")
  19. @QueryMethod(field = "name", method = QueryMethodConstant.LIKE)
  20. private String name;
  21. /**
  22. * 这里没有@QueryMethod注解则如果age有值,则默认查询条件为 age=值
  23. */
  24. @ApiModelProperty(value = "年龄")
  25. private Integer age;
  26. /**
  27. * 假如要查询 (值1 < age < 值2)则可以采用如下方式添加两个属性minAge和maxAge,
  28. * ‘ @QueryMethod 注解的field是数据表字段名,method是查询方式
  29. * 假如minAge = 18,maxAge=25,则通过CommonQueryPageUtils工具类会构建出的sql为 18<age AND age>25
  30. */
  31. @ApiModelProperty(value = "年龄下限")
  32. @QueryMethod(field = "age", method = QueryMethodConstant.GT)
  33. private String minAge;
  34. @ApiModelProperty(value = "年龄上限")
  35. @QueryMethod(field = "age", method = QueryMethodConstant.LT)
  36. private String maxAge;
  37. }

16、先在数据库中添加几条测试数据,然后启动项目后打开http://localhost:8080/swagger-ui.html

  1. insert into `t_user`(`id`,`name`,`age`) values
  2. (1,'小二',20),
  3. (2,'张三',20),
  4. (3,'李四',20),
  5. (4,'王五',35),
  6. (5,'小六',18);

Spring Boot整合Mybatis Plus和Swagger2的教程详解

17、按上图填入查询条件,然后点击“Execute”执行

Spring Boot整合Mybatis Plus和Swagger2的教程详解

返回的Response body:

  1. {
  2. "code": "0",
  3. "msg": "成功!",
  4. "data": {
  5. "records": [
  6. {
  7. "id": 5,
  8. "name": "小六",
  9. "age": 18
  10. },
  11. {
  12. "id": 1,
  13. "name": "小二",
  14. "age": 20
  15. },
  16. {
  17. "id": 2,
  18. "name": "张三",
  19. "age": 20
  20. },
  21. {
  22. "id": 3,
  23. "name": "李四",
  24. "age": 20
  25. }
  26. ],
  27. "total": 4,
  28. "size": 10,
  29. "current": 1,
  30. "orders": [
  31. {
  32. "column": "age",
  33. "asc": true
  34. }
  35. ],
  36. "optimizeCountSql": true,
  37. "hitCount": false,
  38. "countId": null,
  39. "maxLimit": null,
  40. "searchCount": true,
  41. "pages": 1
  42. }
  43. }

通过上面的返回结果可以看出我们带条件带排序的的分页查询功能是ok的!!!

感谢你看完了此篇博文,如果有什么问题可以评论留言,附上完整代码 点击下载完整代码包

到此这篇关于Spring Boot整合Mybatis Plus和Swagger2的文章就介绍到这了,更多相关Spring Boot整合Mybatis Plus和Swagger2内容请搜索快网idc以前的文章或继续浏览下面的相关文章希望大家以后多多支持快网idc!

原文链接:https://www.cnblogs.com/wqp001/p/14436895.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring Boot整合Mybatis Plus和Swagger2的教程详解 https://www.kuaiidc.com/108393.html

相关文章

发表评论
暂无评论