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

前言:若是你是初學者,請徹底按照個人教程以及代碼來搭建(文末會附上完整的項目代碼包,你能夠直接下載我提供的完整項目代碼包而後自行體驗!),爲了照顧初學者因此貼圖比較多,請耐心跟着教程來,但願這個項目Demo能給你一些幫助,若是以爲寫的還能夠請給個關注和點贊,謝謝!

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

1、pom.xml和application.yml

一、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>

二、在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

2、整合Swagger2

一、添加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;
    }
}

二、新建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";
    }
}

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


3、整合Mybatis Plus

一、如圖建立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);
    }
}

二、在數據庫中建立測試表

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

三、建立實體類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;
}

四、建立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> {
}

五、建立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> {
}

六、建立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 {
}

七、建立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));
    }

}

八、建立枚舉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;
    }
}

九、建立統一的返回結果類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;
}

十、建立常量類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";
}

十一、建立自定義註解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 "";
}

十二、建立構建返回結果工具類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;
    }
}

1三、建立分頁查詢工具類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);
    }
}

1四、建立統一的分頁查詢請求參數類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;
}

1五、建立用戶查詢條件類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;
}

1六、先在數據庫中添加幾條測試數據,而後啓動項目後打開http://localhost:8080/swagger-ui.html

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

1七、按上圖填入查詢條件,而後點擊「Execute」執行

返回的Response body:html

{
  "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的!!!java

感謝你看完了此篇博文,若是有什麼問題能夠評論留言,附上完整代碼 點擊下載完整代碼包

相關文章
相關標籤/搜索