MyBatis-Plus ( MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

1)创建数据库
- DROP TABLE IF EXISTS shuser;
-
- CREATE TABLE shuser
- (
- uid INT(4) NOT NULL COMMENT '主键ID',
- username VARCHAR(30) NOT NULL COMMENT '用户名',
- password VARCHAR(30) NOT NULL COMMENT '密码',
- rid INT(4) NOT NULL COMMENT '角色ID',
- createtime DATE COMMENT '创建时间',
- uodatetime DATE COMMENT '修改时间',
- PRIMARY KEY (uid)
- );
2)配置
pom.xml
- <dependencies>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starterartifactId>
- dependency>
- <dependency>
- <groupId>org.springframework.bootgroupId>
- <artifactId>spring-boot-starter-testartifactId>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>com.baomidougroupId>
- <artifactId>mybatis-plus-boot-starterartifactId>
- <version>最新版本version>
- dependency>
- <dependency>
- <groupId>com.h2databasegroupId>
- <artifactId>h2artifactId>
- <scope>runtimescope>
- dependency>
- dependencies>
application.yml
- # DataSource Config
- spring:
- datasource:
- driver-class-name: org.h2.Driver
- schema: classpath:db/schema-h2.sql
- data: classpath:db/data-h2.sql
- url: jdbc:h2:mem:test
- username: root
- password: test
3) 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

4)编码
编写实体类 shUser.java
- @Data
- @AllArgsConstructor
- public class shUser {
-
- private String uid;
- private String username;
- private String password;
- private String rid;
- private String createtime;
- private String updatetime;
-
- }
编写 Mapper 包下的 UserMapper接口
- @Mapper
- public interface UserMapper extends BaseMapper
{ - }
5)测试

1)@TableName 表名注解
- @TableName("sh_user")
- public class shUser {
-
- private String uid;
- private String username;
- private String password;
- private String rid;
- private String createtime;
- private String updatetime;
-
- }

2)@TableId主键注解
- @TableName("sh_user")
- public class shUser {
- @TableId
- private String uid;
- private String username;
- private String password;
- private String rid;
- private String createtime;
- private String updatetime;
-
- }


3)@TableField字段注解
- @TableName("sh_user")
- public class shUser {
- @TableId
- private String uid;
- @TableField("username")
- private String username;
- private String password;
- private String rid;
- private String createtime;
- private String updatetime;
-
- }
2 查询(1)自定义IBaseService继承IService
- public interface UserService extends IService
{ -
- }
- @Service
- public class UserServiceImpl extends ServiceImpl
implements UserService { - }
(2)注解配置:

(3)测试:


(4)插入:
- // 插入一条记录(选择字段,策略插入)
- boolean save(T entity);
- // 插入(批量)
- boolean saveBatch(Collection
entityList) ; - // 插入(批量)
- boolean saveBatch(Collection
entityList, int batchSize) -
- // TableId 注解存在更新记录,否插入一条记录
- boolean saveOrUpdate(T entity);
- // 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
- boolean saveOrUpdate(T entity, Wrapper
updateWrapper) ; - // 批量修改插入
- boolean saveOrUpdateBatch(Collection
entityList) ; - // 批量修改插入
- boolean saveOrUpdateBatch(Collection
entityList, int batchSize) ;
(5)更新:
- // 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
- boolean update(Wrapper
updateWrapper) ; - // 根据 whereWrapper 条件,更新记录
- boolean update(T updateEntity, Wrapper
whereWrapper) ; - // 根据 ID 选择修改
- boolean updateById(T entity);
- // 根据ID 批量更新
- boolean updateBatchById(Collection
entityList) ; - // 根据ID 批量更新
- boolean updateBatchById(Collection
entityList, int batchSize) ;
(6)删除:
- // 根据 entity 条件,删除记录
- boolean remove(Wrapper
queryWrapper) ; - // 根据 ID 删除
- boolean removeById(Serializable id);
- // 根据 columnMap 条件,删除记录
- boolean removeByMap(Map
columnMap) ; - // 删除(根据ID 批量删除)
- boolean removeByIds(Collection extends Serializable> idList);
(7) 查询:
- // 根据 ID 查询
- T getById(Serializable id);
- // 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
- T getOne(Wrapper
queryWrapper) ; - // 根据 Wrapper,查询一条记录
- T getOne(Wrapper
queryWrapper, boolean throwEx) ; - // 根据 Wrapper,查询一条记录
- Map
getMap(Wrapper queryWrapper) ; - // 根据 Wrapper,查询一条记录
V getObj(Wrapper queryWrapper, Function super Object, V> mapper) ; - // 查询所有
- List
list(); - // 查询列表
- List
list(Wrapper queryWrapper) ; - // 查询(根据ID 批量查询)
- Collection
listByIds(Collection extends Serializable> idList); - // 查询(根据 columnMap 条件)
- Collection
listByMap(Map columnMap) ; - // 查询所有列表
- List
- // 查询列表
- List
- // 查询全部记录
- List
- // 查询全部记录
List listObjs(Function super Object, V> mapper); - // 根据 Wrapper 条件,查询全部记录
- List
- // 根据 Wrapper 条件,查询全部记录
List listObjs(Wrapper queryWrapper, Function super Object, V> mapper) ;

结果:

(8)分页查询:
- // 无条件分页查询
- IPage
page(IPage page) ; - // 条件分页查询
- IPage
page(IPage page, Wrapper queryWrapper) ; - // 无条件分页查询
- IPage
- // 条件分页查询
- IPage
(9)总数查询:
- // 查询总记录数
- int count();
- // 根据 Wrapper 条件,查询总记录数
- int count(Wrapper
queryWrapper) ;
1)自定义Mapper接口继承BaseMapper
- @Mapper
- public interface UserMapper extends BaseMapper
{ - }
2)增删改查
- 1)插入
- // 插入一条记录
- int insert(T entity);
- 2)删除
- // 根据 entity 条件,删除记录
- int delete(@Param(Constants.WRAPPER) Wrapper
wrapper) ; - // 删除(根据ID 批量删除)
- int deleteBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList);
- // 根据 ID 删除
- int deleteById(Serializable id);
- // 根据 columnMap 条件,删除记录
- int deleteByMap(@Param(Constants.COLUMN_MAP) Map
columnMap) ; - 3)更新
- // 根据 whereWrapper 条件,更新记录
- int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) Wrapper
whereWrapper) ; - // 根据 ID 修改
- int updateById(@Param(Constants.ENTITY) T entity);
- 4)查询
- // 根据 ID 查询
- T selectById(Serializable id);
- // 根据 entity 条件,查询一条记录
- T selectOne(@Param(Constants.WRAPPER) Wrapper
queryWrapper) ; - // 查询(根据ID 批量查询)
- List
selectBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList); - // 根据 entity 条件,查询全部记录
- List
selectList(@Param(Constants.WRAPPER) Wrapper queryWrapper) ; - // 查询(根据 columnMap 条件)
- List
selectByMap(@Param(Constants.COLUMN_MAP) Map columnMap) ; - // 根据 Wrapper 条件,查询全部记录
- List
- // 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
- List
-
- // 根据 entity 条件,查询全部记录(并翻页)
- IPage
selectPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper) ; - // 根据 Wrapper 条件,查询全部记录(并翻页)
- IPage
- // 根据 Wrapper 条件,查询总记录数
- Integer selectCount(@Param(Constants.WRAPPER) Wrapper
queryWrapper) ;


- Wrapper 条件构造抽象类
- -- AbstractWrapper 查询条件封装,用于生成 sql 中的 where 语句。
- -- QueryWrapper Entity 对象封装操作类,用于查询。
- -- UpdateWrapper Update 条件封装操作类,用于更新。
- -- AbstractLambdaWrapper 使用 Lambda 表达式封装 wrapper
- -- LambdaQueryWrapper 使用 Lambda 语法封装条件,用于查询。
- -- LambdaUpdateWrapper 使用 Lambda 语法封装条件,用于更新。
常用查询:
1) 比较大小类
eq(R column, Object val); // 等价于 =
ne(R column, Object val); // 等价于 <>
gt(R column, Object val); // 等价于 >
ge(R column, Object val); // 等价于 >=
lt(R column, Object val); // 等价于 <
le(R column, Object val); // 等价于 <=2)范围
between(R column, Object val1, Object val2); // 等价于 between a and b
notBetween(R column, Object val1, Object val2); // 等价于 not between a and b
in(R column, Object... values); // 等价于 字段 IN (v0, v1, ...)
notIn(R column, Object... values); // 等价于 字段 NOT IN (v0, v1, ...)
inSql(R column, Object... values); // 等价于 字段 IN (sql 语句)
notInSql(R column, Object... values); // 等价于 字段 NOT IN (sql 语句)3)模糊匹配
like(R column, Object val); // 等价于 LIKE '%值%'
notLike(R column, Object val); // 等价于 NOT LIKE '%值%'
likeLeft(R column, Object val); // 等价于 LIKE '%值'
likeRight(R column, Object val); // 等价于 LIKE '值%'4)空值比较
isNull(R column); // 等价于 IS NULL
isNotNull(R column); // 等价于 IS NOT NULL5)分组、排序
groupBy(R... columns); // 等价于 GROUP BY 字段, ...
orderByAsc(R... columns); // 等价于 ORDER BY 字段, ... ASC
orderByDesc(R... columns); // 等价于 ORDER BY 字段, ... DESC
having(String sqlHaving, Object... params); // 等价于 HAVING ( sql语句 )6)拼接、嵌套
or(); // 等价于 a or b
or(Consumer consumer); // 等价于 or(a or/and b),or 嵌套
and(Consumer consumer); // 等价于 and(a or/and b),and 嵌套
nested(Consumer consumer); // 等价于 (a or/and b),普通嵌套
apply(String applySql, Object... params); // 拼接sql(若不使用 params 参数,可能存在 sql 注入)
last(String lastSql); // 无视优化规则直接拼接到 sql 的最后,可能存若在 sql 注入。
exists(String existsSql); // 拼接 exists 语句
queryWrapper select条件查询:

UpdateWrapper set、setSql(设置SQL语句)更新:

Mybatis-Plus 3.3.2版本:
1)获取密钥
- String randomKey= AES.generateRandomKey();
- //使用随机密钥加密需要加密的数据,列如数据库url,username,password
- String url = "jdbc:mysql://localhost:3306/mybatisplus?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
- String username = "root";
- String password = "root";
- String aesUrl = AES.encrypt(url, randomKey);
- String aesUsername = AES.encrypt(username, randomKey);
- String aesPassword = AES.encrypt(password, randomKey);
- System.out.println("url:"+aesUrl);
- System.out.println("username:"+aesUsername);
- System.out.println("password:"+aesPassword);
-
2)配置
- spring:
- datasource:
- url: mpw:qRhvCwF4GOqjessEB3G+a5okP+uXXr96wcucn2Pev6Bf1oEMZ1gVpPPhdDmjQqoM
- password: mpw:Hzy5iliJbwDHhjLs1L0j6w==
- username: mpw:Xb+EgsyuYRXw7U7sBJjBpA==
3)启动
/ Jar 启动参数( idea 设置 Program arguments , 服务器可以设置为启动环境变量 )
--mpw.key=key
4)其他防护
注解 @FieldEncrypt 字段加密

- @FieldEncrypt
- private String password;
注解 @FieldSensitive 字段脱敏,内置 手机号、邮箱、银行卡号 等 9 种常用脱敏规则
自定义脱敏
- @FieldSensitive(type = "testStrategy")
- private String username;
-
- @FieldSensitive(type = SensitiveType.mobile)
- private String mobile;
-
-
- @Configuration
- public class SensitiveStrategyConfig {
-
- /**
- * 注入脱敏策略
- */
- @Bean
- public ISensitiveStrategy sensitiveStrategy() {
- // 自定义 testStrategy 类型脱敏处理
- return new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");
- }
- }
- mybatis-mate:
- sharding:
- health: true # 健康检测
- primary: mysql # 默认选择数据源
- datasource:
- mysql: # 数据库组
- - key: node1
- ...
- - key: node2
- cluster: slave # 从库读写分离时候负责 sql 查询操作,主库 master 默认可以不写
- ...
- postgres:
- - key: node1 # 数据节点
- ...
- @Mapper
- @Sharding("mysql")
- public interface UserMapper extends BaseMapper
{ -
- @Sharding("postgres")
- Long selectByUsername(String username);
-
- }