服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Spring Boot整合Mybatis Plus和Swagger2的教程详解

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

2021-08-12 11:58野生D程序猿 Java教程

这篇文章主要介绍了Spring Boot整合Mybatis Plus和Swagger2的教程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

前言:如果你是初学者,请完全按照我的教程以及代码来搭建(文末会附上完整的项目代码包,你可以直接下载我提供的完整项目代码包然后自行体验!),为了照顾初学者所以贴图比较多,请耐心跟着教程来,希望这个项目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.  
  17. <properties>
  18. <!--依赖的版本-->
  19. <java.version>1.8</java.version>
  20. <mysql.version>8.0.13</mysql.version>
  21. <mybatisPlus.version>3.4.1</mybatisPlus.version>
  22. <druid.version>1.0.9</druid.version>
  23. <swagger.version>2.9.2</swagger.version>
  24. <hutool.version>5.5.8</hutool.version>
  25. </properties>
  26.  
  27. <dependencies>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-web</artifactId>
  31. </dependency>
  32.  
  33. <dependency>
  34. <groupId>org.projectlombok</groupId>
  35. <artifactId>lombok</artifactId>
  36. <optional>true</optional>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework.boot</groupId>
  40. <artifactId>spring-boot-starter-test</artifactId>
  41. <scope>test</scope>
  42. </dependency>
  43.  
  44. <!--mysql-->
  45. <dependency>
  46. <groupId>mysql</groupId>
  47. <artifactId>mysql-connector-java</artifactId>
  48. <scope>runtime</scope>
  49. <version>${mysql.version}</version>
  50. </dependency>
  51.  
  52. <!-- MyBatis-Plus-->
  53. <dependency>
  54. <groupId>com.baomidou</groupId>
  55. <artifactId>mybatis-plus-boot-starter</artifactId>
  56. <version>${mybatisPlus.version}</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>com.baomidou</groupId>
  60. <artifactId>mybatis-plus-generator</artifactId>
  61. <version>${mybatisPlus.version}</version>
  62. </dependency>
  63.  
  64. <!--druid-->
  65. <dependency>
  66. <groupId>com.alibaba</groupId>
  67. <artifactId>druid</artifactId>
  68. <version>${druid.version}</version>
  69. </dependency>
  70.  
  71. <!--swagger2-->
  72. <dependency>
  73. <groupId>io.springfox</groupId>
  74. <artifactId>springfox-swagger2</artifactId>
  75. <version>${swagger.version}</version>
  76. </dependency>
  77. <dependency>
  78. <groupId>io.springfox</groupId>
  79. <artifactId>springfox-swagger-ui</artifactId>
  80. <version>${swagger.version}</version>
  81. </dependency>
  82.  
  83. <!--hutool-->
  84. <dependency>
  85. <groupId>cn.hutool</groupId>
  86. <artifactId>hutool-all</artifactId>
  87. <version>${hutool.version}</version>
  88. </dependency>
  89. </dependencies>
  90.  
  91. <build>
  92. <plugins>
  93. <plugin>
  94. <groupId>org.springframework.boot</groupId>
  95. <artifactId>spring-boot-maven-plugin</artifactId>
  96. <configuration>
  97. <excludes>
  98. <exclude>
  99. <groupId>org.projectlombok</groupId>
  100. <artifactId>lombok</artifactId>
  101. </exclude>
  102. </excludes>
  103. </configuration>
  104. </plugin>
  105. </plugins>
  106. </build>

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

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

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

二、整合Swagger2

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

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

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

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

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

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

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

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

4、创建UserMapper.java

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

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

5、创建UserService.java

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

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

6、创建UserServiceImpl.java

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

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

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

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

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

8、创建枚举CodeMsgEnum.java

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

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

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

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

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

10、创建常量类QueryMethodConstant.java

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

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

延伸 · 阅读

精彩推荐