MyBatisPlus是國(guó)產(chǎn)的第三方插件, 它封裝了許多常用的CURDapi,免去了我們寫(xiě)mApper.xml的重復(fù)勞動(dòng),這里介紹了基本的整合SpringBoot和基礎(chǔ)用法。
2|0引入依賴(lài)
在項(xiàng)目中pom文件引入mybatisplus和MySQL驅(qū)動(dòng)依賴(lài),如下圖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-JAVA</artifactId>
<version>8.0.26</version>
</dependency>
3|0配置連接信息
在項(xiàng)目中application.yaml文件中配置數(shù)據(jù)庫(kù)的連接信息
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/didiadmin?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true
username: root
password: 123456
4|0新建兩個(gè)表
本案例通過(guò)一個(gè)完整的業(yè)務(wù)流程來(lái)介紹如何使用mybatispuls,首先在數(shù)據(jù)庫(kù)中新建兩個(gè)表,一個(gè)是字典類(lèi)型表sys_dict_type和一個(gè)字典數(shù)據(jù)表sys_dict_data
CREATE TABLE `sys_dict_type` (
`id` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '標(biāo)識(shí)',
`type_name` VARCHAR (255) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '字典類(lèi)型名稱(chēng)',
`type_code` VARCHAR (255) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '字典類(lèi)型標(biāo)識(shí)',
`description` VARCHAR (255) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '字典類(lèi)型描述',
`enable` CHAR (1) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '是否啟用',
`create_by` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '創(chuàng)建人ID',
`create_name` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '創(chuàng)建人名稱(chēng)',
`create_time` datetime DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
`update_by` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '修改人ID',
`update_name` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '修改人名稱(chēng)',
`update_time` datetime DEFAULT NULL COMMENT '修改時(shí)間',
`remark` VARCHAR (255) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '備注',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = DYNAMIC
CREATE TABLE `sys_dict_data` (
`data_id` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '標(biāo)識(shí)',
`data_label` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '字典標(biāo)簽',
`data_value` CHAR (20) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '字典值',
`type_code` CHAR (20) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '所屬類(lèi)型',
`is_default` CHAR (1) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '是否默認(rèn)',
`update_by` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '修改人ID',
`update_name` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '修改人名稱(chēng)',
`update_time` datetime DEFAULT NULL COMMENT '修改時(shí)間',
`create_by` VARCHAR (255) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '創(chuàng)建人ID',
`create_name` CHAR (19) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '創(chuàng)建人名稱(chēng)',
`create_time` datetime DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
`remark` VARCHAR (255) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '備注',
`enable` CHAR (1) CHARACTER
SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '是否啟用',
PRIMARY KEY (`data_id`) USING BTREE
) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = DYNAMIC
5|0在項(xiàng)目中創(chuàng)建相應(yīng)的實(shí)體類(lèi)
通過(guò)觀察SQL語(yǔ)句發(fā)現(xiàn)兩個(gè)表中有很多相同的字段,所有我們把相同的字段抽離出來(lái),放到一個(gè)基礎(chǔ)的實(shí)體類(lèi)中,其他實(shí)體類(lèi)通過(guò)集成方式獲取公共的字段。
5|1創(chuàng)建基礎(chǔ)實(shí)體類(lèi)
package com.didiplus.common.base;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc: 基 礎(chǔ) 實(shí) 體 類(lèi)
*/
@Data
public class BaseDomain implements Serializable {
/**
* 創(chuàng)建時(shí)間
*/
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 創(chuàng)建人
*/
@TableField(value = "create_by", fill = FieldFill.INSERT)
private String createBy;
/**
* 創(chuàng)建人名稱(chēng)
*/
@TableField(value = "create_name", fill = FieldFill.INSERT)
private String createName;
/**
* 修改時(shí)間
*/
@TableField(value = "update_time", fill = FieldFill.UPDATE)
private LocalDateTime updateTime;
/**
* 修改人
*/
@TableField(value = "update_by", fill = FieldFill.UPDATE)
private String updateBy;
/**
* 修改人名稱(chēng)
*/
@TableField(value = "update_name", fill = FieldFill.UPDATE)
private String updateName;
/**
* 備注
*/
private String remark;
}
@TableField 是mybatisplus中的一個(gè)注解,后面會(huì)講解到的。
基礎(chǔ)實(shí)體類(lèi)創(chuàng)建好了,接著我們把剩下的兩個(gè)實(shí)體類(lèi)也一同創(chuàng)建吧。
5|2SysDictType實(shí)體類(lèi)
package com.didiplus.modules.sys.domain;
import com.didiplus.common.base.BaseDomain;
import com.didiplus.common.base.ValidGroup;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.*;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/25
* Desc: 字典類(lèi)型領(lǐng)域模型
*/
@Data
@ApiModel(value = "字典類(lèi)型")
public class SysDictType extends BaseDomain {
/**
* 標(biāo)識(shí)
*/
@Null(groups = ValidGroup.Crud.Create.class)
@NotNull(groups = ValidGroup.Crud.Update.class,message = "字典ID不能為空")
@ApiModelProperty("ID")
private String id;
/**
* 字典名稱(chēng)
*/
@NotBlank(message = "字典名稱(chēng)必填項(xiàng)")
@ApiModelProperty(value = "字典名稱(chēng)",example = "用戶ID")
private String typeName;
/**
* 字典類(lèi)型
*/
@NotBlank(message = "字典編碼不能為空")
@ApiModelProperty(value = "字典編碼")
private String typeCode;
/**
* 字典描述
*/
@ApiModelProperty(value = "字典描述")
private String description;
/**
* 字典可用狀態(tài)
*/
@NotBlank(message = "字典狀態(tài)不能為空")
@ApiModelProperty(value = "字典狀態(tài)")
private Boolean enable;
}
5|3SysDictData實(shí)體類(lèi)
package com.didiplus.modules.sys.domain;
import com.baomidou.mybatisplus.annotation.TableField;
import com.didiplus.common.base.BaseDomain;
import com.didiplus.common.base.ValidGroup;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc: 字典值領(lǐng)域模型
*/
@Data
public class SysDictData extends BaseDomain {
/**
* id 編號(hào)
*/
@Null(groups = ValidGroup.Crud.Create.class)
@NotNull(groups = ValidGroup.Crud.Update.class,message = "字典數(shù)據(jù)ID不能為空")
@ApiModelProperty("ID")
@TableField(value = "data_id")
private String dataId;
/**
* 字典顯示
*/
@NotBlank(message = "字典數(shù)據(jù)名稱(chēng)必填項(xiàng)")
@ApiModelProperty(value = "字典數(shù)據(jù)名稱(chēng)")
private String dataLabel;
/**
* 字典值
*/
@NotBlank(message = "字典數(shù)據(jù)值不能為空")
@ApiModelProperty(value = "字典數(shù)據(jù)值")
private String dataValue;
/**
* 字典類(lèi)型
*/
@ApiModelProperty(value = "字典編碼")
@NotBlank(message = "字典數(shù)據(jù)值不能為空")
private String typeCode;
/**
* 是否為默認(rèn)
*/
@ApiModelProperty(value = "字典編碼")
@NotBlank(message = "字典數(shù)據(jù)值不能為空")
private String isDefault;
/**
* 是否啟用
*/
@NotBlank(message = "字典狀態(tài)不能為空")
@ApiModelProperty(value = "字典數(shù)據(jù)狀態(tài)")
private Boolean enable;
}
6|0創(chuàng)建DAO繼承MybatisPlus增強(qiáng)接口
為兩個(gè)實(shí)體類(lèi)中分別添加DAO繼承MybatisPlus增強(qiáng)接口,這樣就可以集成了增刪改查的功能了。
6|1SysDictTypeMapper
package com.didiplus.modules.sys.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.didiplus.modules.sys.domain.SysDictType;
import org.Apache.ibatis.annotations.Mapper;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc: 字典類(lèi)型接口
*/
@Mapper
public interface SysDictTypeMapper extends BaseMapper<SysDictType> {
}
6|2SysDictDataMapper
package com.didiplus.modules.sys.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.didiplus.modules.sys.domain.SysDictData;
import org.apache.ibatis.annotations.Mapper;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc: 字典數(shù)據(jù)接口
*/
@Mapper
public interface SysDictDataMapper extends BaseMapper<SysDictData> {
}
7|0進(jìn)一步封裝到Service層
7|1定義Service接口中的抽象方法
SysDictDataService
package com.didiplus.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.didiplus.modules.sys.domain.SysDictData;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc:
*/
public interface SysDictDataService extends IService<SysDictData> {
}
SysDictTypeService
package com.didiplus.modules.sys.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.didiplus.modules.sys.domain.SysDictType;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc:
*/
public interface SysDictTypeService extends IService<SysDictType> {
}
7|2實(shí)現(xiàn)Service接口中的方法
SysDictTypeServiceImpl
package com.didiplus.modules.sys.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.didiplus.modules.sys.domain.SysDictType;
import com.didiplus.modules.sys.mapper.SysDictTypeMapper;
import com.didiplus.modules.sys.service.SysDictTypeService;
import org.springframework.stereotype.Service;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc:
*/
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {
}
SysDictDataServiceImpl
package com.didiplus.modules.sys.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.didiplus.modules.sys.domain.SysDictType;
import com.didiplus.modules.sys.mapper.SysDictTypeMapper;
import com.didiplus.modules.sys.service.SysDictTypeService;
import org.springframework.stereotype.Service;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc:
*/
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {
}
8|0在控制層上進(jìn)行增刪改查操作
8|1SysDictTypeController
package com.didiplus.modules.sys.controller;
import com.didiplus.common.base.ValidGroup;
import com.didiplus.modules.sys.domain.SysDictType;
import com.didiplus.modules.sys.service.SysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/25
* Desc: 數(shù)據(jù)字典控制器
*/
@RestController
@Api(tags = "數(shù)據(jù)字典")
@RequestMapping("/api/sys/dictType")
public class SysDictTypeController {
@Autowired
SysDictTypeService sysDictTypeService;
@ApiOperation("字典添加")
@PostMapping("/add")
public String add(@Validated(value = ValidGroup.Crud.Create.class) @RequestBody SysDictType sysDictType) {
return sysDictTypeService.save(sysDictType)? "添加成功":"添加失敗";
}
@ApiOperation("字典修改")
@PutMapping("/edit")
public String edit(@Validated(value = ValidGroup.Crud.Update.class) @RequestBody SysDictType sysDictType) {
return sysDictTypeService.updateById(sysDictType)? "修改成功":"修改失敗";
}
@ApiOperation("字典刪除")
@DeleteMapping("/del/{id}")
public String del( @PathVariable String id) {
return sysDictTypeService.removeById(id)? "刪除成功":"刪除失敗";
}
}
體驗(yàn)效果
新增數(shù)據(jù)
修改數(shù)據(jù)
刪除數(shù)據(jù)
9|0自動(dòng)填充功能
原理:
- 實(shí)現(xiàn)元對(duì)象處理器接口:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
- 注解填充字段 @TableField(.. fill = FieldFill.INSERT)生成器策略部分也可以配置!
9|1自定義實(shí)現(xiàn)類(lèi) DomainInterceptor
package com.didiplus.common.web.interceptor;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/5/4
* Desc: 字 段 填 充 攔 截 器
*/
@Component
public class DomainInterceptor implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
createField(metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
updateField(metaObject);
}
/**
* @Field 創(chuàng)建時(shí)間
* */
public void createField(MetaObject metaObject){
this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
}
/**
* @Field 修改時(shí)間
* */
public void updateField(MetaObject metaObject) {
this.strictUpdateFill(metaObject,"updateTime",LocalDateTime.class,LocalDateTime.now());
}
}
10|0分頁(yè)查詢
10|1添加分頁(yè)插件
package com.didiplus.common.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/5/4
* Desc: mybatis-plus分頁(yè)插件
*/
@Configuration
public class MyBatisPlusConfig {
/**
* mybatis-plus分頁(yè)插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
10|2定義分頁(yè)接口
package com.didiplus.modules.sys.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.didiplus.common.web.domain.PageDomain;
import com.didiplus.modules.sys.domain.SysDictType;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc: 數(shù)據(jù)字典類(lèi)型服務(wù)類(lèi)
*/
public interface SysDictTypeService extends IService<SysDictType> {
IPage<SysDictType> page(PageDomain pageDomain);
}
10|3實(shí)現(xiàn)分頁(yè)接口
package com.didiplus.modules.sys.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.didiplus.common.web.domain.PageDomain;
import com.didiplus.modules.sys.domain.SysDictType;
import com.didiplus.modules.sys.mapper.SysDictTypeMapper;
import com.didiplus.modules.sys.service.SysDictTypeService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/4/29
* Desc:
*/
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {
@Resource
SysDictTypeMapper sysDictTypeMapper;
@Override
public IPage<SysDictType> page(PageDomain pageDomain) {
IPage<SysDictType> page = new Page<>(pageDomain.getPage(),pageDomain.getLimit());
return sysDictTypeMapper.selectPage(page,null);
}
}
10|4控制層調(diào)用
@RestController
@Api(tags = "數(shù)據(jù)字典")
@RequestMapping("/api/sys/dictType")
public class SysDictTypeController {
@Autowired
SysDictTypeService sysDictTypeService;
@ApiOperation("字典分頁(yè)查詢")
@GetMapping
public IPage list(@RequestBody PageDomain pageDomain){
return sysDictTypeService.page(pageDomain);
}
}
PageDomain定義了分頁(yè)接收的兩個(gè)參數(shù)
PageDomain類(lèi)
package com.didiplus.common.web.domain;
import lombok.Data;
/**
* Author: didiplus
* Email: 972479352@qq.com
* CreateTime: 2022/5/4
* Desc: 分 頁(yè) 參 數(shù) 封 裝
*/
@Data
public class PageDomain {
/**
* 當(dāng)前頁(yè)
*/
private Integer page;
/**
* 每頁(yè)數(shù)量
*/
private Integer limit;
}
10|5體驗(yàn)效果