SpringBoot2.3.0整合MyBatis-Plus3.4.0和Swagger3.0

liu320yj發表於2020-10-02

簡介

MyBatis是常用的持久層框架,深得廣大程式設計師的喜愛,MyBatis-Plus是在MyBatis的基礎之上實現的增強版持久層框架,開發更加簡潔,效率更高。詳見MyBatis-Plus官網
本文主要介紹基於SpringBoot2.3.0整合MyBatis-Plus3.4.0,並使用Swagger3.0測試

資料庫表

新建資料庫springboot並在其下建立測試表sys_user

DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user`  (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主鍵ID',
  `login_name` varchar(30) NOT NULL COMMENT '登入名',
  `user_name` varchar(30) NULL DEFAULT NULL COMMENT '使用者名稱',
  `password` varchar(64) NOT NULL COMMENT '密碼',
  `sex` tinyint(2) UNSIGNED NOT NULL DEFAULT 10 COMMENT '性別10:男;11:女;12:其他',
  `avatar` varchar(100) NULL DEFAULT NULL COMMENT '頭像地址',
  `status` tinyint(2) UNSIGNED NOT NULL DEFAULT 10 COMMENT '賬號狀態10:正常;20:鎖定;30:登出',
  `del_flag` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 COMMENT '刪除標識0(true):未刪除;1(false):已刪除',
  `create_by` varchar(30) NULL DEFAULT NULL COMMENT '建立者',
  `create_time` timestamp(0) NULL DEFAULT NULL COMMENT '建立時間',
  `update_by` varchar(30) NULL DEFAULT NULL COMMENT '更新者',
  `update_time` timestamp(0) NULL DEFAULT NULL COMMENT '更新時間',
  `remark` varchar(100) NULL DEFAULT NULL COMMENT '備註',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci;

新建maven專案,引入相關依賴

核心依賴引入如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-generator</artifactId>
        <version>3.4.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-engine-core</artifactId>
        <version>2.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
</dependencies>

引入MyBatis-Plus依賴包後,不需要再引入MyBatis依賴包,否則會引起jar包衝突

新增配置資訊

在resources目錄下新建application.yml檔案,配置如下:

server:
  port: 8080
spring:
  application:
    name: springboot-mybatis-plus
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://192.168.108.11:3306/springboot?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
    username: root
    password: root
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
mybatis-plus:
  mapper-locations: classpath:mapper/**/*Mapper.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  type-aliases-package: com.xlhj.plus.entity

新建配置檔案

MyBatis-Plus是通過外掛來實現分頁功能的,需要配置相關的外掛,程式碼如下:

@Configuration
@MapperScan(basePackages = "com.xlhj.*.mapper")
public class MybatisPlusConfig {
    /**
     * 分頁外掛
     * @return
     */
    @Bean
    public MybatisPlusInterceptor interceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

Swagger配置檔案如下:

@Configuration
@EnableOpenApi
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot整合mybatis-plus")
                .description("springboot2.3.0整合mybatis-plus")
                .contact(new Contact("lcj", null, "123@qq.com"))
                .version("1.0")
                .build();
    }
}

Swagger3.0的寫法跟之前有較大的區別,這點請注意

主要程式碼

使用MyBatis-Plus自帶的程式碼生成工具可以生成entity、dao、service、controller檔案結構,MyBatis-Plus提供常用的增刪改查方法,只需要自己寫一些複雜的SQL即可,實體類程式碼如下:

@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="SysUser物件", description="使用者表")
public class SysUser implements Serializable {

    private static final long serialVersionUID = -4892850743805515016L;

    @ApiModelProperty(value = "主鍵ID")
    @TableId(value = "id", type = IdType.AUTO)//主鍵生成策略:自動生成
    private Long id;

    @ApiModelProperty(value = "登入名")
    private String loginName;

    @ApiModelProperty(value = "使用者名稱")
    private String userName;

    @ApiModelProperty(value = "密碼")
    private String password;

    @ApiModelProperty(value = "性別10:男;11:女;12:其他")
    private Integer sex;

    @ApiModelProperty(value = "頭像地址")
    private String avatar;

    @ApiModelProperty(value = "賬號狀態10:正常;20:鎖定;30:登出")
    private Integer status;

    @TableLogic(value = "0", delval = "1")//開啟邏輯刪除功能
    @ApiModelProperty(value = "刪除標識0(true):未刪除;1(false):已刪除")
    private Boolean delFlag;

    @ApiModelProperty(value = "建立者")
    private String createBy;

    @ApiModelProperty(value = "建立時間")
    @TableField(value = "create_time", fill = FieldFill.INSERT)//設定時間自動填充
    private LocalDateTime createTime;

    @ApiModelProperty(value = "更新者")
    private String updateBy;

    @ApiModelProperty(value = "更新時間")
    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;

    @ApiModelProperty(value = "備註")
    private String remark;
}

Controller程式碼如下:

@RestController
@RequestMapping("/plus/user")
public class SysUserController {

    @Autowired
    private SysUserService userService;

    /**
     * 查詢所有使用者列表
     * @return
     */
    @GetMapping("/findAll")
    @ApiOperation(value = "查詢所有使用者列表")
    public AjaxResult findAllUser() {
        List<SysUser> userList = userService.list(null);
        return AjaxResult.ok().data("items", userList);
    }

    /**
     * 分頁查詢使用者資訊
     * @param current
     * @param limit
     * @return
     */
    @GetMapping("/pageListUser/{current}/{limit}")
    @ApiOperation(value = "分頁查詢使用者資訊")
    public AjaxResult pageListUser(@PathVariable long current, @PathVariable long limit) {
        Page<SysUser> userPage = new Page<SysUser>(current, limit);
        userService.page(userPage, null);
        long total = userPage.getTotal();
        List<SysUser> records = userPage.getRecords();
        return AjaxResult.ok().data("total", total).data("rows", records);
    }

    /**
     * 新增使用者資訊
     * @param user
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "新增使用者")
    public AjaxResult add(@RequestBody SysUser user) {
        user.setPassword(Md5Utils.toHex(Md5Utils.md5(user.getPassword())));
        boolean flag = userService.save(user);
        if (flag) {
            return AjaxResult.ok();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 根據ID查詢使用者資訊
     * @param id
     * @return
     */
    @GetMapping("getUserById/{id}")
    @ApiOperation(value = "根據ID查詢使用者資訊")
    public AjaxResult getUserById(@PathVariable Long id) {
        SysUser user = userService.getById(id);
        return AjaxResult.ok().data("user", user);
    }

    /**
     * 修改使用者資訊
     * @param user
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改使用者")
    public AjaxResult update(@RequestBody SysUser user) {
        userService.updateById(user);
        return AjaxResult.ok();
    }

    /**
     * 邏輯刪除使用者資訊
     * @param id
     * @return
     */
    @DeleteMapping("/remove/{id}")
    @ApiOperation(value = "邏輯刪除使用者資訊")
    public AjaxResult remove(@ApiParam(name = "id", value = "主鍵ID", required = true) @PathVariable Long id) {
        boolean flag = userService.removeById(id);
        if (flag) {
            return AjaxResult.ok();
        } else {
            return AjaxResult.error();
        }
    }
}

主啟動類程式碼如下:

@SpringBootApplication
@MapperScan(basePackages = "com.xlhj.*.mapper")
public class MybatisPlusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }
}

啟動專案,訪問Swagger-UI頁面http://localhost:8080/swagger-ui/index.html如下所示:
Swagger介面
完整程式碼請參考碼雲地址

相關文章