手把手教你Spring Boot整合Mybatis Plus和Swagger2

野生D程式猿發表於2021-02-23

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

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

一、pom.xml和application.yml

1、pom.xml中新增相關依賴,這裡我把我的pom.xml程式碼貼出來

<?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.3</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>study</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>study</name>
<description>Demo project for Spring Boot</description>

<properties>
    <!--依賴的版本-->
    <java.version>1.8</java.version>
    <mysql.version>8.0.13</mysql.version>
    <mybatisPlus.version>3.4.1</mybatisPlus.version>
    <druid.version>1.0.9</druid.version>
    <swagger.version>2.9.2</swagger.version>
    <hutool.version>5.5.8</hutool.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </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>

    <!--mysql-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
        <version>${mysql.version}</version>
    </dependency>

   <!-- MyBatis-Plus-->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>${mybatisPlus.version}</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>${mybatisPlus.version}</version>
    </dependency>

    <!--druid-->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>${druid.version}</version>
    </dependency>

    <!--swagger2-->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${swagger.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${swagger.version}</version>
    </dependency>

    <!--hutool-->
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>${hutool.version}</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <excludes>
                    <exclude>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                    </exclude>
                </excludes>
            </configuration>
        </plugin>
    </plugins>
</build>

2、在resources下新建application.yml檔案,並新增如下配置

# 配置埠
server:
  port: 8080

#----------------druid資料來源配置-----------------------
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      #這裡跟pom裡面mysql-connector版本相關8.0之後用com.mysql.cj.jdbc.Driver,之前用com.mysql.jdbc.Driver
      driver-class-name: com.mysql.cj.jdbc.Driver
      #這裡改成你自己的資料庫名稱以及賬號和密碼
      url: jdbc:mysql://127.0.0.1:3306/study?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
      username: root
      password: 123456
      initialSize: 10
      minIdle: 10
      maxActive: 30
      # 配置獲取連線等待超時的時間
      maxWait: 60000
      # 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一個連線在池中最小生存的時間,單位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1 FROM DUAL
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 開啟PSCache,並且指定每個連線上PSCache的大小
      poolPreparedStatements: true
      # 配置監控統計攔截的filters,去掉後監控介面sql無法統計,'wall'用於防火牆
      #filters: stat,wall,log4j
      # 通過connectProperties屬性來開啟mergeSql功能;慢SQL記錄
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      # 合併多個DruidDataSource的監控資料
      useGlobalDataSourceStat: true

#----------------mybatis plus配置-----------------------
mybatis-plus:
  # xml掃描,多個目錄用逗號或者分號分隔(告訴 Mapper 所對應的 XML 檔案位置)
  mapper-locations: classpath:mapper/*.xml
  configuration:
    # 是否開啟自動駝峰命名規則對映:從資料庫列名到Java屬性駝峰命名的類似對映
    map-underscore-to-camel-case: true
    # 如果查詢結果中包含空值的列,則 MyBatis 在對映的時候,不會對映這個欄位
    call-setters-on-nulls: true
    # 這個配置會將執行的sql列印出來,在開發或測試的時候可以用
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 實體掃描,多個package用逗號或者分號分隔(這裡更改為你的實體類存放路徑)
  typeAliasesPackage: com.example.study.model.entity
  global-config:
    db-config:
      #主鍵型別 AUTO:"資料庫ID自增" INPUT:"使用者輸入ID",ID_WORKER:"全域性唯一ID (數字型別唯一ID)", UUID:"全域性唯一ID UUID";
      id-type: auto
      #欄位策略 IGNORED:"忽略判斷"  NOT_NULL:"非 NULL 判斷")  NOT_EMPTY:"非空判斷"
      field-strategy: NOT_EMPTY
      #資料庫型別
      db-type: MYSQL
      # 邏輯刪除配置
      # 刪除前
      logic-not-delete-value: 1
      # 刪除後
      logic-delete-value: 0

#----------------swagger配置-----------------------
swagger:
  #生產環境改為false(改為false後swagger-ui.html則無法訪問)
  enable: true
#解決Swagger2 異常 NumberFormatException:For input string:""
logging:
  level:
    io:
      swagger:
        models:
          parameters:
            AbstractSerializableParameter: ERROR

二、整合Swagger2

1、新增swagger的配置類SwaggerConfig.java

package com.example.study.config;

import io.swagger.annotations.Api;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

/**
 * Swagger配置類
 *
 * @author 154594742@qq.com
 * @date: 2021/2/22 10:02:00
 */
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class SwaggerConfig {
    /**
     * 建立API應用
     * apiInfo() 增加API相關資訊
     * 通過select()函式返回一個ApiSelectorBuilder例項,用來控制哪些介面暴露給Swagger來展現,
     * 本例採用指定掃描的包路徑來定義指定要建立API的目錄。
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(this.apiInfo())
                .select()
                //設定選擇器,選擇帶Api介面類的類
                .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                //api包掃描
                .apis(RequestHandlerSelectors.basePackage("com.example.study"))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(securitySchemes());
    }

    /**
     * 建立該API的基本資訊(這些基本資訊會展現在文件頁面中)
     * 訪問地址:http://ip:埠/swagger-ui.html
     *
     * @return ApiInfo
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("demo專案")
                .description("demo專案API文件")
                .termsOfServiceUrl("http://localhost")
                .version("1.0")
                .build();
    }

    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeyList= new ArrayList<>();
        //apiKeyList.add(new ApiKey("token", "令牌", "header"));
        return apiKeyList;
    }
}

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

package com.example.study.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 首頁控制器
 * @author 154594742@qq.com
 * @date: 2021/2/22 10:02:00
 */
@Api(tags = "首頁控制器")
@RestController
public class IndexController {

    @ApiOperation("首頁html")
    @GetMapping("/")
    public String index(){
        return "hello index";
    }
}

3、啟動StudyApplication.java後訪問 http://localhost:8080/swagger-ui.html ,出現第二圖所示則表示swagger整合完成


三、整合Mybatis Plus

1、如圖建立MybatisPlusConfi.java配置分頁外掛

package com.example.study.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置MybatisPlus分頁外掛
 *
 * @author 154594742@qq.com
 * @date: 2021/2/22 10:02:00
 */
@Configuration
@MapperScan("com.example.study.mapper")
public class MybatisPlusConfig {

    /**
     * Mybatis-plus3.4.0版本過後使用MybatisPlusInterceptor分頁外掛
     * 注意:DbType.MYSQL必須為自己使用的資料庫型別,否則分頁不生效
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 設定useDeprecatedExecutor = false 避免快取出現問題
     * @return
     */
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}

2、在資料庫中建立測試表

CREATE TABLE `t_user` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `age` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

3、建立實體類UserEntity.java

package com.example.study.model.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 使用者資訊實體類
 *
 * @author 154594742@qq.com
 * @date: 2021/2/22 10:02:00
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "UserEntity", description = "使用者實體")
@TableName("t_user")
public class UserEntity implements Serializable {

    private static final long serialVersionUID = 6928834261563057243L;

    /**
     * 唯一標識,自增主鍵
     */
    @ApiModelProperty(value = "id")
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 姓名
     */
    @ApiModelProperty(value = "姓名")
    @TableField("name")
    private String name;

    /**
     * 年齡
     */
    @ApiModelProperty(value = "年齡")
    @TableField("age")
    private Integer age;
}

4、建立UserMapper.java

package com.example.study.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.study.model.entity.UserEntity;

/**
 * @author 154594742@qq.com
 */
public interface UserMapper extends BaseMapper<UserEntity> {
}

5、建立UserService.java

package com.example.study.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.study.model.entity.UserEntity;

/**
 * @author 154594742@qq.com
 */
public interface UserService extends IService<UserEntity> {
}

6、建立UserServiceImpl.java

package com.example.study.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.study.model.entity.UserEntity;
import com.example.study.mapper.UserMapper;
import com.example.study.service.UserService;
import org.springframework.stereotype.Service;

/**
 * @author 154594742@qq.com
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
}

7、建立UserController.java(這裡編譯器會提示一些錯誤暫時不用管,因為缺少一些類的程式碼)

package com.example.study.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.study.model.entity.UserEntity;
import com.example.study.model.param.UserParam;
import com.example.study.model.vo.ResponseVo;
import com.example.study.service.UserService;
import com.example.study.util.CommonQueryPageUtils;
import com.example.study.util.BuildResponseUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 使用者控制器
 *
 * @author 154594742@qq.com
 * @date: 2021/2/22 10:02:00
 */

@RestController
@Api(tags = "使用者控制器")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("新增")
    @PostMapping("user")
    public ResponseVo<?> add(UserEntity entity) {
        return userService.save(entity) ? BuildResponseUtils.success() : BuildResponseUtils.error();
    }

    @ApiOperation("通過id查詢")
    @GetMapping("user/{id}")
    public ResponseVo<UserEntity> getById(@PathVariable String id) {
        return BuildResponseUtils.buildResponse(userService.getById(id));
    }

    @ApiOperation("修改")
    @PutMapping("user")
    public ResponseVo<?> update(UserEntity entity) {
        return userService.updateById(entity) ? BuildResponseUtils.success() : BuildResponseUtils.error();
    }

    @ApiOperation("通過id刪除")
    @DeleteMapping("user/{id}")
    public ResponseVo<?> delete(@PathVariable String id) {
        return userService.removeById(id) ? BuildResponseUtils.success() : BuildResponseUtils.error();
    }


    @ApiOperation("分頁查詢")
    @GetMapping("userPage")
    public ResponseVo<IPage<UserEntity>> selectPage(UserParam param) {
        return BuildResponseUtils.buildResponse(CommonQueryPageUtils.commonQueryPage(param, userService));
    }

}

8、建立列舉CodeMsgEnum.java

package com.example.study.enums;

/**
 * 異常類code常量(code值不要重複)
 *
 * @author 154594742@qq.com
 * @date: 2021/2/22 9:42:00
 */
public enum CodeMsgEnum {
    //請求成功
    SUCCESS("0","成功!"),
    //系統異常
    FAIL("1","失敗!"),
    //以下是業務異常
    LOGIN_NO_PASS("1001","使用者名稱或密碼錯誤"),
    ;

    /**
     * 狀態碼
     */
    public String code;

    /**
     * 狀態碼對應資訊
     */
    public String msg;

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

9、建立統一的返回結果類ResponseVo.java

package com.example.study.model.vo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * 統一的返回物件VO
 *
 * @author 154594742@qq.com
 * @date: 2021/2/22 10:02:00
 */

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "ResponseVo", description = "統一的返回物件")
public class ResponseVo<T> implements Serializable {
    private static final long serialVersionUID = 7748070653645596712L;
    /**
     * 狀態碼
     */
    @ApiModelProperty(value = "狀態碼")
    private String code;

    /**
     * 狀態碼對應描述資訊
     */
    @ApiModelProperty(value = "狀態碼對應描述資訊")
    private String msg;

    /**
     * 資料
     */
    @ApiModelProperty(value = "資料")
    private T data;
}

10、建立常量類QueryMethodConstant.java

package com.example.study.constant;

/**
 * mybatis plus常用的查詢方式
 * @author 154594742@qq.com
 * @date 2021/2/23 11:24
 */

public interface QueryMethodConstant {
    /**
     * 相同
     */
    String EQ = "EQ";

    /**
     * 不相同
     */
    String NE = "NE";

    /**
     * 相似,左右模糊(like '%值%')
     */
    String LIKE = "LIKE";

    /**
     * 相似,左模糊(like '%值')
     */
    String LIKE_LIFT = "LIKE_LIFT";

    /**
     * 相似,右模糊(like '值%')
     */
    String LIKE_RIGHT = "LIKE_RIGHT";

    /**
     * 不相似 (not like '%值%')
     */
    String NOT_LIKE = "NOT_LIKE";

    /**
     * 大於
     */
    String GT = "GT";

    /**
     * 大於等於
     */
    String GE = "GE";

    /**
     * 小於
     */
    String LT = "LT";

    /**
     * 小於等於
     */
    String LE = "LE";
}

11、建立自定義註解QueryMethod.java(用於後續的通用分頁查詢工具類)

package com.example.study.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 查詢方式的自定義註解
 * @author 154594742@qq.com
 * @date 2021/2/23 11:24
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.FIELD)
public @interface QueryMethod {

    /**
     * 欄位名
     */
    String field() default "";

    /**
     * 匹配方式
     */
    String method() default "";
}

12、建立構建返回結果工具類BuildResponseUtils.java

package com.example.study.util;

import com.example.study.enums.CodeMsgEnum;
import com.example.study.model.vo.ResponseVo;

/**
 * 構建返回結果工具類
 *
 * @author 154594742@qq.com
 * @date: 2021/2/22 10:02:00
 */
public final class BuildResponseUtils {

    /**
     * 構建正確請求的response
     *
     * @return ResponseVo 統一的返回結果
     */
    public static ResponseVo<?> success() {
        ResponseVo<?> response = new ResponseVo<>();
        response.setCode(CodeMsgEnum.SUCCESS.code);
        response.setMsg(CodeMsgEnum.SUCCESS.msg);
        return response;
    }

    /**
     * 構建業務異常的response
     * @param codeMsgEnum 列舉
     * @return ResponseVo 統一的返回結果
     */
    public static ResponseVo<?> success(CodeMsgEnum codeMsgEnum) {
        ResponseVo<?> response = new ResponseVo<>();
        response.setCode(codeMsgEnum.code);
        response.setMsg(codeMsgEnum.msg);
        return response;
    }

    /**
     * 構建自定義code和msg的業務異常
     *
     * @param code 自定義code
     * @param msg 自定義msg
     * @return ResponseVo 統一的返回結果
     */
    public static ResponseVo<?> success(String code, String msg) {
        ResponseVo<?> response = new ResponseVo<>();
        response.setCode(code);
        response.setMsg(msg);
        return response;
    }

    /**
     * 構建系統異常的response(只用於系統異常)
     * @return ResponseVo 統一的返回結果
     */
    public static ResponseVo<?> error() {
        ResponseVo<?> response = new ResponseVo<>();
        response.setCode(CodeMsgEnum.FAIL.code);
        response.setMsg(CodeMsgEnum.FAIL.msg);
        return response;
    }

    /**
     * 構建返回結果
     * @param obj 結果資料
     * @param <T> 結果資料的泛型
     * @return ResponseVo 統一的返回結果
     */
    public static <T> ResponseVo<T> buildResponse(T obj) {
        ResponseVo<T> response = new ResponseVo<>();
        response.setData(obj);
        response.setCode(CodeMsgEnum.SUCCESS.code);
        response.setMsg(CodeMsgEnum.SUCCESS.msg);
        return response;
    }
}

13、建立分頁查詢工具類CommonQueryPageUtils.java(本人自己封裝的,功能可能不是很完善,但是基本的單表查詢夠用了)

package com.example.study.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.study.annotation.QueryMethod;
import com.example.study.constant.QueryMethodConstant;
import com.example.study.model.param.PageParam;

import java.lang.reflect.Field;
import java.util.Locale;

/**
 * 分頁查詢工具類
 *
 * @author 154594742@qq.com
 * @date: 2021/2/22 10:02:00
 */
public final class CommonQueryPageUtils {

    /**
     * 正序
     */
    private static final String ASC = "asc";

    /**
     * 倒序
     */
    private static final String DESC = "desc";

    /**
     * 通用的帶排序功能的分頁查詢
     */
    public static <T> IPage<T> commonQueryPage(PageParam param, IService<T> service) {
        //構建page
        //根據傳入的排序設定order
        //排序欄位(格式:欄位名:排序方式,欄位名:排序方式 (asc正序,desc倒序) 示例:id:desc,age:asc)
        Page<T> page = new Page<>(param.getPage(), param.getLimit());
        String orders = param.getOrders();
        if (StringUtils.isNotBlank(orders)) {
            String[] splitArr = orders.split(",");
            for (String str : splitArr) {
                if (StringUtils.isBlank(str)) {
                    continue;
                }
                String[] strArr = str.split(":");
                if (strArr.length != 2 || StringUtils.isBlank(strArr[0]) || StringUtils.isBlank(strArr[1])) {
                    continue;
                }
                if (ASC.equals(strArr[1].toLowerCase(Locale.ROOT))) {
                    page.addOrder(OrderItem.asc(strArr[0]));
                    continue;
                }
                if (DESC.equals(strArr[1].toLowerCase(Locale.ROOT))) {
                    page.addOrder(OrderItem.desc(strArr[0]));
                }
            }
        }
        //根據自定義註解構建queryWrapper
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        Class<? extends PageParam> clazz = param.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            //設定物件的訪問許可權,保證對private的屬性可以訪問
            field.setAccessible(true);
            QueryMethod annotation = field.getAnnotation(QueryMethod.class);
            try {
                //屬性沒有值則跳過
                if (null == field.get(param)) {
                    continue;
                }
                //沒有加@QueryMethod 預設屬性名為欄位名,預設匹配方式為eq
                if (null == annotation) {
                    queryWrapper.eq(field.getName(), field.get(param));
                    continue;
                }

                switch (annotation.method()) {
                    case QueryMethodConstant.EQ:
                        queryWrapper.eq(annotation.field(), field.get(param));
                        break;
                    case QueryMethodConstant.NE:
                        queryWrapper.ne(annotation.field(), field.get(param));
                        break;
                    case QueryMethodConstant.LIKE:
                        queryWrapper.like(annotation.field(), field.get(param));
                        break;
                    case QueryMethodConstant.LIKE_LIFT:
                        queryWrapper.likeLeft(annotation.field(), field.get(param));
                        break;
                    case QueryMethodConstant.LIKE_RIGHT:
                        queryWrapper.likeRight(annotation.field(), field.get(param));
                        break;
                    case QueryMethodConstant.GT:
                        queryWrapper.gt(annotation.field(), field.get(param));
                        break;
                    case QueryMethodConstant.GE:
                        queryWrapper.ge(annotation.field(), field.get(param));
                        break;
                    case QueryMethodConstant.LT:
                        queryWrapper.lt(annotation.field(), field.get(param));
                        break;
                    case QueryMethodConstant.LE:
                        queryWrapper.le(annotation.field(), field.get(param));
                        break;
                    default:
                        ;
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return service.page(page, queryWrapper);
    }
}

14、建立統一的分頁查詢請求引數類PageParam.java

package com.example.study.model.param;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.LinkedHashMap;

/**
 * 統一的分頁查詢請求引數
 *
 * @author 154594742@qq.com
 * @date 2021/2/22 17:24
 */

@Data
@ApiModel(value = "PageParam", description = "分頁引數")
public class PageParam {
    /**
     * 頁碼
     */
    @ApiModelProperty(value = "頁碼,不傳則預設1")
    private Integer page = 1;

    /**
     * 每頁條數
     */
    @ApiModelProperty(value = "每頁條數,不傳則預設10")
    private Integer limit = 10;

    /**
     * 排序欄位(格式:欄位名:排序方式,欄位名:排序方式 (asc正序,desc倒序) 示例:id:desc,age:asc)
     */
    @ApiModelProperty(value = "排序欄位(格式:欄位名:排序方式,欄位名:排序方式 (asc正序,desc倒序) 示例:id:desc,age:asc)")
    private String orders;
}

15、建立使用者查詢條件類UserParam.java繼承PageParam(以後分頁查詢的引數類都要繼承PageParam)

package com.example.study.model.param;

import com.example.study.annotation.QueryMethod;
import com.example.study.constant.QueryMethodConstant;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * 使用者查詢條件類(需要根據哪些欄位查詢就新增哪些欄位)
 * @author 154594742@qq.com
 * @date 2021/2/22 17:24
 */

@Data
@ApiModel(value = "UserParam", description = "使用者查詢條件")
public class UserParam extends PageParam {

    /**
     * 通過@QueryMethod註解來控制匹配的方式,這裡查詢條件為 name like ‘%值%’
     */
    @ApiModelProperty(value = "姓名")
    @QueryMethod(field = "name", method = QueryMethodConstant.LIKE)
    private String name;

    /**
     * 這裡沒有@QueryMethod註解則如果age有值,則預設查詢條件為 age=值
     */
    @ApiModelProperty(value = "年齡")
    private Integer age;

    /**
     * 假如要查詢 (值1 < age < 值2)則可以採用如下方式新增兩個屬性minAge和maxAge,
     * ‘ @QueryMethod 註解的field是資料表欄位名,method是查詢方式
     * 假如minAge = 18,maxAge=25,則通過CommonQueryPageUtils工具類會構建出的sql為 18<age AND age>25
     */
    @ApiModelProperty(value = "年齡下限")
    @QueryMethod(field = "age", method = QueryMethodConstant.GT)
    private String minAge;

    @ApiModelProperty(value = "年齡上限")
    @QueryMethod(field = "age", method = QueryMethodConstant.LT)
    private String maxAge;
}

16、先在資料庫中新增幾條測試資料,然後啟動專案後開啟 http://localhost:8080/swagger-ui.html

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

17、按上圖填入查詢條件,然後點選“Execute”執行

返回的Response body:

{
  "code": "0",
  "msg": "成功!",
  "data": {
    "records": [
      {
        "id": 5,
        "name": "小六",
        "age": 18
      },
      {
        "id": 1,
        "name": "小二",
        "age": 20
      },
      {
        "id": 2,
        "name": "張三",
        "age": 20
      },
      {
        "id": 3,
        "name": "李四",
        "age": 20
      }
    ],
    "total": 4,
    "size": 10,
    "current": 1,
    "orders": [
      {
        "column": "age",
        "asc": true
      }
    ],
    "optimizeCountSql": true,
    "hitCount": false,
    "countId": null,
    "maxLimit": null,
    "searchCount": true,
    "pages": 1
  }
}

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

感謝你看完了此篇博文,如果有什麼問題可以評論留言,附上完整程式碼 點選下載完整程式碼包

相關文章