国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Spring Boot整合Mybatis Plus和Swagger2的教程詳解

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

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

這篇文章主要介紹了Spring Boot整合Mybatis Plus和Swagger2的教程,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

前言:如果你是初學(xué)者,請完全按照我的教程以及代碼來搭建(文末會附上完整的項(xiàng)目代碼包,你可以直接下載我提供的完整項(xiàng)目代碼包然后自行體驗(yàn)!),為了照顧初學(xué)者所以貼圖比較多,請耐心跟著教程來,希望這個項(xiàng)目Demo能給你一些幫助,如果覺得寫的還可以請給個關(guān)注和點(diǎn)贊,謝謝!

題外話:這是我第一篇用markdown來寫的博文,格式不好的地方請見諒

一、pom.xml和application.yml

1、pom.xml中添加相關(guān)依賴,這里我把我的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數(shù)據(jù)源配置-----------------------
  6. spring:
  7. datasource:
  8. type: com.alibaba.druid.pool.DruidDataSource
  9. druid:
  10. #這里跟pom里面mysql-connector版本相關(guān)8.0之后用com.mysql.cj.jdbc.Driver,之前用com.mysql.jdbc.Driver
  11. driver-class-name: com.mysql.cj.jdbc.Driver
  12. #這里改成你自己的數(shù)據(jù)庫名稱以及賬號和密碼
  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. # 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
  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. # 配置監(jiān)控統(tǒng)計攔截的filters,去掉后監(jiān)控界面sql無法統(tǒng)計,'wall'用于防火墻
  32. #filters: stat,wall,log4j
  33. # 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
  34. connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
  35. # 合并多個DruidDataSource的監(jiān)控數(shù)據(jù)
  36. useGlobalDataSourceStat: true
  37.  
  38. #----------------mybatis plus配置-----------------------
  39. mybatis-plus:
  40. # xml掃描,多個目錄用逗號或者分號分隔(告訴 Mapper 所對應(yīng)的 XML 文件位置)
  41. mapper-locations: classpath:mapper/*.xml
  42. configuration:
  43. # 是否開啟自動駝峰命名規(guī)則映射:從數(shù)據(jù)庫列名到Java屬性駝峰命名的類似映射
  44. map-underscore-to-camel-case: true
  45. # 如果查詢結(jié)果中包含空值的列,則 MyBatis 在映射的時候,不會映射這個字段
  46. call-setters-on-nulls: true
  47. # 這個配置會將執(zhí)行的sql打印出來,在開發(fā)或測試的時候可以用
  48. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  49. # 實(shí)體掃描,多個package用逗號或者分號分隔(這里更改為你的實(shí)體類存放路徑)
  50. typeAliasesPackage: com.example.study.model.entity
  51. global-config:
  52. db-config:
  53. #主鍵類型 AUTO:"數(shù)據(jù)庫ID自增" INPUT:"用戶輸入ID",ID_WORKER:"全局唯一ID (數(shù)字類型唯一ID)", UUID:"全局唯一ID UUID";
  54. id-type: auto
  55. #字段策略 IGNORED:"忽略判斷" NOT_NULL:"非 NULL 判斷") NOT_EMPTY:"非空判斷"
  56. field-strategy: NOT_EMPTY
  57. #數(shù)據(jù)庫類型
  58. db-type: MYSQL
  59. # 邏輯刪除配置
  60. # 刪除前
  61. logic-not-delete-value: 1
  62. # 刪除后
  63. logic-delete-value: 0
  64.  
  65. #----------------swagger配置-----------------------
  66. swagger:
  67. #生產(chǎn)環(huán)境改為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. * 創(chuàng)建API應(yīng)用
  31. * apiInfo() 增加API相關(guān)信息
  32. * 通過select()函數(shù)返回一個ApiSelectorBuilder實(shí)例,用來控制哪些接口暴露給Swagger來展現(xiàn),
  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. //設(shè)置選擇器,選擇帶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. * 創(chuàng)建該API的基本信息(這些基本信息會展現(xiàn)在文檔頁面中)
  53. * 訪問地址:http://ip:端口/swagger-ui.html
  54. *
  55. * @return ApiInfo
  56. */
  57. private ApiInfo apiInfo() {
  58. return new ApiInfoBuilder().title("demo項(xiàng)目")
  59. .description("demo項(xiàng)目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,出現(xiàn)第二圖所示則表示swagger整合完成

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

三、整合Mybatis Plus

1、如圖創(chuàng)建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必須為自己使用的數(shù)據(jù)庫類型,否則分頁不生效
  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. * 設(shè)置useDeprecatedExecutor = false 避免緩存出現(xiàn)問題
  34. * @return
  35. */
  36. @Bean
  37. public ConfigurationCustomizer configurationCustomizer() {
  38. return configuration -> configuration.setUseDeprecatedExecutor(false);
  39. }
  40. }

2、在數(shù)據(jù)庫中創(chuàng)建測試表

  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、創(chuàng)建實(shí)體類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. * 用戶信息實(shí)體類
  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 = "用戶實(shí)體")
  26. @TableName("t_user")
  27. public class UserEntity implements Serializable {
  28.  
  29. private static final long serialVersionUID = 6928834261563057243L;
  30.  
  31. /**
  32. * 唯一標(biāo)識,自增主鍵
  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、創(chuàng)建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、創(chuàng)建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、創(chuàng)建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、創(chuàng)建UserController.java(這里編譯器會提示一些錯誤暫時不用管,因?yàn)槿鄙僖恍╊惖拇a)

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、創(chuàng)建枚舉CodeMsgEnum.java

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

  1. package com.example.study.enums;
  2.  
  3. /**
  4. * 異常類code常量(code值不要重復(fù))
  5. *
  6. * @author 154594742@qq.com
  7. * @date: 2021/2/22 9:42:00
  8. */
  9. public enum CodeMsgEnum {
  10. //請求成功
  11. SUCCESS("0","成功!"),
  12. //系統(tǒng)異常
  13. FAIL("1","失敗!"),
  14. //以下是業(yè)務(wù)異常
  15. LOGIN_NO_PASS("1001","用戶名或密碼錯誤"),
  16. ;
  17.  
  18. /**
  19. * 狀態(tài)碼
  20. */
  21. public String code;
  22.  
  23. /**
  24. * 狀態(tài)碼對應(yīng)信息
  25. */
  26. public String msg;
  27.  
  28. CodeMsgEnum(String code, String msg) {
  29. this.code = code;
  30. this.msg = msg;
  31. }
  32. }

9、創(chuàng)建統(tǒng)一的返回結(jié)果類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. * 統(tǒng)一的返回對象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 = "統(tǒng)一的返回對象")
  22. public class ResponseVo<T> implements Serializable {
  23. private static final long serialVersionUID = 7748070653645596712L;
  24. /**
  25. * 狀態(tài)碼
  26. */
  27. @ApiModelProperty(value = "狀態(tài)碼")
  28. private String code;
  29.  
  30. /**
  31. * 狀態(tài)碼對應(yīng)描述信息
  32. */
  33. @ApiModelProperty(value = "狀態(tài)碼對應(yīng)描述信息")
  34. private String msg;
  35.  
  36. /**
  37. * 數(shù)據(jù)
  38. */
  39. @ApiModelProperty(value = "數(shù)據(jù)")
  40. private T data;
  41. }

10、創(chuàng)建常量類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、創(chuàng)建自定義注解QueryMethod.java(用于后續(xù)的通用分頁查詢工具類)

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、創(chuàng)建構(gòu)建返回結(jié)果工具類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. * 構(gòu)建返回結(jié)果工具類
  8. *
  9. * @author 154594742@qq.com
  10. * @date: 2021/2/22 10:02:00
  11. */
  12. public final class BuildResponseUtils {
  13.  
  14. /**
  15. * 構(gòu)建正確請求的response
  16. *
  17. * @return ResponseVo 統(tǒng)一的返回結(jié)果
  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. * 構(gòu)建業(yè)務(wù)異常的response
  28. * @param codeMsgEnum 枚舉
  29. * @return ResponseVo 統(tǒng)一的返回結(jié)果
  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. * 構(gòu)建自定義code和msg的業(yè)務(wù)異常
  40. *
  41. * @param code 自定義code
  42. * @param msg 自定義msg
  43. * @return ResponseVo 統(tǒng)一的返回結(jié)果
  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. * 構(gòu)建系統(tǒng)異常的response(只用于系統(tǒng)異常)
  54. * @return ResponseVo 統(tǒng)一的返回結(jié)果
  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. * 構(gòu)建返回結(jié)果
  65. * @param obj 結(jié)果數(shù)據(jù)
  66. * @param <T> 結(jié)果數(shù)據(jù)的泛型
  67. * @return ResponseVo 統(tǒng)一的返回結(jié)果
  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、創(chuàng)建分頁查詢工具類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. //構(gòu)建page
  39. //根據(jù)傳入的排序設(shè)置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. //根據(jù)自定義注解構(gòu)建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. //設(shè)置對象的訪問權(quán)限,保證對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 默認(rèn)屬性名為字段名,默認(rèn)匹配方式為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、創(chuàng)建統(tǒng)一的分頁查詢請求參數(shù)類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. * 統(tǒng)一的分頁查詢請求參數(shù)
  11. *
  12. * @author 154594742@qq.com
  13. * @date 2021/2/22 17:24
  14. */
  15.  
  16. @Data
  17. @ApiModel(value = "PageParam", description = "分頁參數(shù)")
  18. public class PageParam {
  19. /**
  20. * 頁碼
  21. */
  22. @ApiModelProperty(value = "頁碼,不傳則默認(rèn)1")
  23. private Integer page = 1;
  24.  
  25. /**
  26. * 每頁條數(shù)
  27. */
  28. @ApiModelProperty(value = "每頁條數(shù),不傳則默認(rèn)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、創(chuàng)建用戶查詢條件類UserParam.java繼承PageParam(以后分頁查詢的參數(shù)類都要繼承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. * 用戶查詢條件類(需要根據(jù)哪些字段查詢就添加哪些字段)
  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有值,則默認(rèn)查詢條件為 age=值
  28. */
  29. @ApiModelProperty(value = "年齡")
  30. private Integer age;
  31.  
  32. /**
  33. * 假如要查詢 (值1 < age < 值2)則可以采用如下方式添加兩個屬性minAge和maxAge,
  34. * ‘ @QueryMethod 注解的field是數(shù)據(jù)表字段名,method是查詢方式
  35. * 假如minAge = 18,maxAge=25,則通過CommonQueryPageUtils工具類會構(gòu)建出的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、先在數(shù)據(jù)庫中添加幾條測試數(shù)據(jù),然后啟動項(xiàng)目后打開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、按上圖填入查詢條件,然后點(diǎn)擊“Execute”執(zhí)行

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. }

通過上面的返回結(jié)果可以看出我們帶條件帶排序的的分頁查詢功能是ok的!!!

感謝你看完了此篇博文,如果有什么問題可以評論留言,附上完整代碼 點(diǎn)擊下載完整代碼包

到此這篇關(guān)于Spring Boot整合Mybatis Plus和Swagger2的文章就介紹到這了,更多相關(guān)Spring Boot整合Mybatis Plus和Swagger2內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产专区在线看 | 久久99精品国产麻豆婷婷洗澡 | 欧美 日韩 成人 | 美女爽到呻吟久久久久 | 婷婷国产在线观看 | 在线观看国产视频 | 在线一区二区三区四区 | 日韩精品色 | 亚洲一区二区在线 | 一区视频| 午夜视频在线播放 | 国产精品女教师av久久 | ts人妖另类精品视频系列 | 免费观看一级毛片 | 免费毛片视频 | 老师的朋友2 | 在线观看免费视频黄 | 欧美一级做a爰片久久高潮 免费在线毛片 | 国产精品久久久久久中文字 | 欧美成人免费 | 日本女人高潮视频 | 日韩电影在线看 | 欧美男人的天堂 | 久久国产精品系列 | 国产福利在线播放 | 国产一区二区三区欧美 | 这里有精品视频 | 一本大的之伊人 | 午夜你懂得 | 亚洲成人av| 国产伦精品一区二区三区 | 国产中文字幕网 | 中文区永久区 | av国产精品 | 自拍视频在线 | 亚洲精品国产a久久久久久 99热少妇 | 不卡一区 | 精品久久一二三区 | 九九热精品视频在线观看 | 欧美在线免费视频 | 色香阁99久久精品久久久 |