1. 快速入门 1.1 简介最好的学习方式就是官方文档:https://baomidou.com/pages/24112f/#%E7%89%B9%E6%80%A7
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1.1.1 特性- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
- 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
- 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
任何能使用 MyBatis 进行 CRUD, 并且支持标准 SQL 的数据库,具体支持情况如下。
- MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb
- 达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DuS1g0rL-1654418423221)(D:MyConfigurationle.chenAppDataRoamingTyporatypora-user-imagesimage-20220601190250375.png)]
1.2 快速开始我们将通过一个简单的 Demo 来阐述 MyBatis-Plus 的强大功能,在此之前,我们假设您已经:
- 拥有 Java 开发环境以及相应 IDE
- 熟悉 Spring Boot
- 熟悉 Maven
这里的依赖包括MP依赖,代码生成器,模板引擎等。
1.2.2 配置文件com.baomidou mybatis-plus-boot-starter 3.4.1 mysql mysql-connector-java runtime org.projectlombok lombok 1.18.24 com.baomidou mybatis-plus-generator 3.4.1 org.apache.velocity velocity-engine-core 2.1 org.freemarker freemarker 2.3.31
配置数据库相关链接信息:
spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8 spring.datasource.username=root spring.datasource.password=1234561.2.3 代码生成器
我们这里为了简化开发,直接使用代码生成器来生成相关的实体类,dao及service。
这里需要注意的是修改相关目录,然后运行之后输入数据库中已经存在的表名即可。如果不是你想要的目录,则可以自行修改。
public class CodeGenerator {
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
//注意这个springboot-mybatis-plus-demo,由于我是在子模块下生成代码的,所以多加了一层目录;单层项目不需要加。
gc.setOutputDir(projectPath + "/springboot-mybatis-plus-demo" + "/src/main/java");
gc.setAuthor("chen");
gc.setOpen(false);
//实体属性 Swagger2 注解
gc.setSwagger2(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setParent("com.example.springbootmybatisplusdemo");
pc.setEntity("dal.model");
pc.setMapper("dal.mapper");
pc.setService("service");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setEntityLombokModel(true);
// 公共父类
// strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");
//表名
strategy.setInclude(scanner("表名").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
}
1.2.4 测试
在测试之前,需要在启动类中添加扫描注解。
@SpringBootApplication
@MapperScan(value = {"com.example.springbootmybatisplusdemo.dal.mapper"})
public class SpringbootMybatisPlusDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisPlusDemoApplication.class, args);
}
}
然后在测试类中测试即可成功。
@SpringBootTest
class SpringbootMybatisPlusDemoApplicationTests {
@Autowired
private IUserService userService;
@Test
void contextLoads() {
System.out.println(userService.list());
}
}
2. 核心功能
2.1 CRUD接口
2.1.1 Service CRUD 接口
2.1.1.1 Save说明:
- 通用 Service CRUD 封装IService (opens new window)接口,进一步封装 CRUD 采用 get 查询单行 remove 删除 list 查询集合 page 分页 前缀命名方式区分 Mapper 层避免混淆,
- 泛型 T 为任意实体对象
- 建议如果存在自定义通用 Service 方法的可能,请创建自己的 IBaseService 继承 Mybatis-Plus 提供的基类
- 对象 Wrapper 为 条件构造器
// 插入一条记录(选择字段,策略插入) boolean save(T entity); // 插入(批量) boolean saveBatch(CollectionentityList); // 插入(批量) boolean saveBatch(Collection entityList, int batchSize);
| 类型 | 参数名 | 描述 |
|---|---|---|
| T | entity | 实体对象 |
| Collection | entityList | 实体对象集合 |
| int | batchSize | 插入批次数量 |
// TableId 注解存在更新记录,否插入一条记录 boolean saveOrUpdate(T entity); // 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法 boolean saveOrUpdate(T entity, WrapperupdateWrapper); // 批量修改插入 boolean saveOrUpdateBatch(Collection entityList); // 批量修改插入 boolean saveOrUpdateBatch(Collection entityList, int batchSize);
| 类型 | 参数名 | 描述 |
|---|---|---|
| T | entity | 实体对象 |
| Wrapper | updateWrapper | 实体对象封装操作类 UpdateWrapper |
| Collection | entityList | 实体对象集合 |
| int | batchSize | 插入批次数量 |
// 根据 entity 条件,删除记录 boolean remove(WrapperqueryWrapper); // 根据 ID 删除 boolean removeById(Serializable id); // 根据 columnMap 条件,删除记录 boolean removeByMap(Map columnMap); // 删除(根据ID 批量删除) boolean removeByIds(Collection extends Serializable> idList);
| 类型 | 参数名 | 描述 |
|---|---|---|
| Wrapper | queryWrapper | 实体包装类 QueryWrapper |
| Serializable | id | 主键 ID |
| Map | columnMap | 表字段 map 对象 |
| Collection extends Serializable> | idList | 主键 ID 列表 |
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset boolean update(WrapperupdateWrapper); // 根据 whereWrapper 条件,更新记录 boolean update(T updateEntity, Wrapper whereWrapper); // 根据 ID 选择修改 boolean updateById(T entity); // 根据ID 批量更新 boolean updateBatchById(Collection entityList); // 根据ID 批量更新 boolean updateBatchById(Collection entityList, int batchSize);
| 类型 | 参数名 | 描述 |
|---|---|---|
| Wrapper | updateWrapper | 实体对象封装操作类 UpdateWrapper |
| T | entity | 实体对象 |
| Collection | entityList | 实体对象集合 |
| int | batchSize | 更新批次数量 |
// 根据 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);
| 类型 | 参数名 | 描述 |
|---|---|---|
| Serializable | id | 主键 ID |
| Wrapper | queryWrapper | 实体对象封装操作类 QueryWrapper |
| boolean | throwEx | 有多个 result 是否抛出异常 |
| T | entity | 实体对象 |
| Function super Object, V> | mapper | 转换函数 |
// 查询所有 Listlist(); // 查询列表 List list(Wrapper queryWrapper); // 查询(根据ID 批量查询) Collection listByIds(Collection extends Serializable> idList); // 查询(根据 columnMap 条件) Collection listByMap(Map columnMap); // 查询所有列表 List
| 类型 | 参数名 | 描述 |
|---|---|---|
| Wrapper | queryWrapper | 实体对象封装操作类 QueryWrapper |
| Collection extends Serializable> | idList | 主键 ID 列表 |
| Map | columnMap | 表字段 map 对象 |
| Function super Object, V> | mapper | 转换函数 |
// 无条件分页查询 IPagepage(IPage page); // 条件分页查询 IPage page(IPage page, Wrapper queryWrapper); // 无条件分页查询 IPage > pageMaps(IPage page); // 条件分页查询 IPage > pageMaps(IPage page, Wrapper queryWrapper);
| 类型 | 参数名 | 描述 |
|---|---|---|
| IPage | page | 翻页对象 |
| Wrapper | queryWrapper | 实体对象封装操作类 QueryWrapper |
// 查询总记录数 int count(); // 根据 Wrapper 条件,查询总记录数 int count(Wrapper2.1.1.9 ChainqueryWrapper);
query
// 链式查询 普通 QueryChainWrapperquery(); // 链式查询 lambda 式。注意:不支持 Kotlin LambdaQueryChainWrapper lambdaQuery(); // 示例: query().eq("column", value).one(); lambdaQuery().eq(Entity::getId, value).list();
update
// 链式更改 普通 UpdateChainWrapper2.1.2 Mapper CRUD 接口update(); // 链式更改 lambda 式。注意:不支持 Kotlin LambdaUpdateChainWrapper lambdaUpdate(); // 示例: update().eq("column", value).remove(); lambdaUpdate().eq(Entity::getId, value).update(entity);
2.1.2.1 Insert说明:
- 通用 CRUD 封装BaseMapper (opens new window)接口,为 Mybatis-Plus 启动时自动解析实体表关系映射转换为 Mybatis 内部对象注入容器
- 泛型 T 为任意实体对象
- 参数 Serializable 为任意类型主键 Mybatis-Plus 不推荐使用复合主键约定每一张表都有自己的唯一 id 主键
- 对象 Wrapper 为 条件构造器
// 插入一条记录 int insert(T entity);
| 类型 | 参数名 | 描述 |
|---|---|---|
| T | entity | 实体对象 |
// 根据 entity 条件,删除记录 int delete(@Param(Constants.WRAPPER) Wrapperwrapper); // 删除(根据ID 批量删除) int deleteBatchIds(@Param(Constants.COLLECTION) Collection extends Serializable> idList); // 根据 ID 删除 int deleteById(Serializable id); // 根据 columnMap 条件,删除记录 int deleteByMap(@Param(Constants.COLUMN_MAP) Map columnMap);
| 类型 | 参数名 | 描述 |
|---|---|---|
| Wrapper | wrapper | 实体对象封装操作类(可以为 null) |
| Collection extends Serializable> | idList | 主键 ID 列表(不能为 null 以及 empty) |
| Serializable | id | 主键 ID |
| Map | columnMap | 表字段 map 对象 |
// 根据 whereWrapper 条件,更新记录 int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) WrapperwhereWrapper); // 根据 ID 修改 int updateById(@Param(Constants.ENTITY) T entity);
| 类型 | 参数名 | 描述 |
|---|---|---|
| T | entity | 实体对象 (set 条件值,可为 null) |
| Wrapper | updateWrapper | 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句) |
// 根据 ID 查询 T selectById(Serializable id); // 根据 entity 条件,查询一条记录 T selectOne(@Param(Constants.WRAPPER) WrapperqueryWrapper); // 查询(根据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 > selectMaps(@Param(Constants.WRAPPER) Wrapper queryWrapper); // 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值 List selectObjs(@Param(Constants.WRAPPER) Wrapper queryWrapper); // 根据 entity 条件,查询全部记录(并翻页) IPage selectPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper); // 根据 Wrapper 条件,查询全部记录(并翻页) IPage > selectMapsPage(IPage page, @Param(Constants.WRAPPER) Wrapper queryWrapper); // 根据 Wrapper 条件,查询总记录数 Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper);
| 类型 | 参数名 | 描述 |
|---|---|---|
| Serializable | id | 主键 ID |
| Wrapper | queryWrapper | 实体对象封装操作类(可以为 null) |
| Collection extends Serializable> | idList | 主键 ID 列表(不能为 null 以及 empty) |
| Map | columnMap | 表字段 map 对象 |
| IPage | page | 分页查询条件(可以为 RowBounds.DEFAULT) |
说明:
- 实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 需要项目中已注入对应实体的BaseMapper
操作步骤:
- 继承 Model(opens new window)
class User extends Model{ // fields... }
- 调用CRUD方法(演示部分api,仅供参考)
User user = new User(); user.insert(); user.selectAll(); user.updateById(); user.deleteById(); // ...2.2 条件构造器
说明:
- 以下出现的第一个入参boolean condition表示该条件是否加入最后生成的sql中,例如:query.like(StringUtils.isNotBlank(name), Entity::getName, name) .eq(age!=null && age >= 0, Entity::getAge, age)
- 以下代码块内的多个方法均为从上往下补全个别boolean类型的入参,默认为true
- 以下出现的泛型Param均为Wrapper的子类实例(均具有AbstractWrapper的所有方法)
- 以下方法在入参中出现的R为泛型,在普通wrapper中是String,在LambdaWrapper中是函数(例:Entity::getId,Entity为实体类,getId为字段id的getMethod)
- 以下方法入参中的R column均表示数据库字段,当R具体类型为String时则为数据库字段名(字段名是数据库关键字的自己用转义符包裹!)!而不是实体类数据字段名!!!,另当R具体类型为SFunction时项目runtime不支持eclipse自家的编译器!!!
- 以下举例均为使用普通wrapper,入参为Map和List的均以json形式表现!
- 使用中如果入参的Map或者List为空,则不会加入最后生成的sql中!!!
- 有任何疑问就点开源码看,看不懂函数的点击我学习新知识(opens new window)
2.2.1 AbstractWrapper警告:
不支持以及不赞成在 RPC 调用中把 Wrapper 进行传输
- wrapper 很重
- 传输 wrapper 可以类比为你的 controller 用 map 接收值(开发一时爽,维护火葬场)
- 正确的 RPC 调用姿势是写一个 DTO 进行传输,被调用方再根据 DTO 执行相应的操作
- 我们拒绝接受任何关于 RPC 传输 Wrapper 报错相关的 issue 甚至 pr
2.2.1.1 allEq说明:
QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类
用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件
注意: entity 生成的 where 条件与 使用各个 api 生成的 where 条件没有任何关联行为
allEq(Mapparams) allEq(Map params, boolean null2IsNull) allEq(boolean condition, Map params, boolean null2IsNull)
-
全部
eq(或个别isNull)
个别参数说明:
params : key为数据库字段名,value为字段值
null2IsNull : 为true则在map的value为null时调用 isNull 方法,为false时则忽略value为null的 -
例1: allEq({id:1,name:"老王",age:null})—>id = 1 and name = '老王' and age is null
-
例2: allEq({id:1,name:"老王",age:null}, false)—>id = 1 and name = '老王'
allEq(BiPredicatefilter, Map params) allEq(BiPredicate filter, Map params, boolean null2IsNull) allEq(boolean condition, BiPredicate filter, Map params, boolean null2IsNull)
个别参数说明:
filter : 过滤函数,是否允许字段传入比对条件中
params 与 null2IsNull : 同上
- 例1: allEq((k,v) -> k.indexOf("a") >= 0, {id:1,name:"老王",age:null})—>name = '老王' and age is null
- 例2: allEq((k,v) -> k.indexOf("a") >= 0, {id:1,name:"老王",age:null}, false)—>name = '老王'
eq(R column, Object val) eq(boolean condition, R column, Object val)
- 等于 =
- 例: eq("name", "老王")—>name = '老王'
ne(R column, Object val) ne(boolean condition, R column, Object val)
- 不等于 <>
- 例: ne("name", "老王")—>name <> '老王'
gt(R column, Object val) gt(boolean condition, R column, Object val)
- 大于 >
- 例: gt("age", 18)—>age > 18
ge(R column, Object val) ge(boolean condition, R column, Object val)
- 大于等于 >=
- 例: ge("age", 18)—>age >= 18
lt(R column, Object val) lt(boolean condition, R column, Object val)
- 小于 <
- 例: lt("age", 18)—>age < 18
le(R column, Object val) le(boolean condition, R column, Object val)
- 小于等于 <=
- 例: le("age", 18)—>age <= 18
between(R column, Object val1, Object val2) between(boolean condition, R column, Object val1, Object val2)
- BETWEEN 值1 AND 值2
- 例: between("age", 18, 30)—>age between 18 and 30
notBetween(R column, Object val1, Object val2) notBetween(boolean condition, R column, Object val1, Object val2)
- NOT BETWEEN 值1 AND 值2
- 例: notBetween("age", 18, 30)—>age not between 18 and 30
like(R column, Object val) like(boolean condition, R column, Object val)
- LIKE ‘%值%’
- 例: like("name", "王")—>name like '%王%'
notLike(R column, Object val) notLike(boolean condition, R column, Object val)
- NOT LIKE ‘%值%’
- 例: notLike("name", "王")—>name not like '%王%'
likeLeft(R column, Object val) likeLeft(boolean condition, R column, Object val)
- LIKE ‘%值’
- 例: likeLeft("name", "王")—>name like '%王'
likeRight(R column, Object val) likeRight(boolean condition, R column, Object val)
- LIKE ‘值%’
- 例: likeRight("name", "王")—>name like '王%'
isNull(R column) isNull(boolean condition, R column)
- 字段 IS NULL
- 例: isNull("name")—>name is null
isNotNull(R column) isNotNull(boolean condition, R column)
- 字段 IS NOT NULL
- 例: isNotNull("name")—>name is not null
in(R column, Collection> value) in(boolean condition, R column, Collection> value)
- 字段 IN (value.get(0), value.get(1), …)
- 例: in("age",{1,2,3})—>age in (1,2,3)
in(R column, Object... values) in(boolean condition, R column, Object... values)
- 字段 IN (v0, v1, …)
- 例: in("age", 1, 2, 3)—>age in (1,2,3)
notIn(R column, Collection> value) notIn(boolean condition, R column, Collection> value)
- 字段 NOT IN (value.get(0), value.get(1), …)
- 例: notIn("age",{1,2,3})—>age not in (1,2,3)
notIn(R column, Object... values) notIn(boolean condition, R column, Object... values)
- 字段 NOT IN (v0, v1, …)
- 例: notIn("age", 1, 2, 3)—>age not in (1,2,3)
inSql(R column, String inValue) inSql(boolean condition, R column, String inValue)
- 字段 IN ( sql语句 )
- 例: inSql("age", "1,2,3,4,5,6")—>age in (1,2,3,4,5,6)
- 例: inSql("id", "select id from table where id < 3")—>id in (select id from table where id < 3)
notInSql(R column, String inValue) notInSql(boolean condition, R column, String inValue)
- 字段 NOT IN ( sql语句 )
- 例: notInSql("age", "1,2,3,4,5,6")—>age not in (1,2,3,4,5,6)
- 例: notInSql("id", "select id from table where id < 3")—>id not in (select id from table where id < 3)
groupBy(R... columns) groupBy(boolean condition, R... columns)
- 分组:GROUP BY 字段, …
- 例: groupBy("id", "name")—>group by id,name
orderByAsc(R... columns) orderByAsc(boolean condition, R... columns)
- 排序:ORDER BY 字段, … ASC
- 例: orderByAsc("id", "name")—>order by id ASC,name ASC
orderByDesc(R... columns) orderByDesc(boolean condition, R... columns)
- 排序:ORDER BY 字段, … DESC
- 例: orderByDesc("id", "name")—>order by id DESC,name DESC
orderBy(boolean condition, boolean isAsc, R... columns)
- 排序:ORDER BY 字段, …
- 例: orderBy(true, true, "id", "name")—>order by id ASC,name ASC
having(String sqlHaving, Object... params) having(boolean condition, String sqlHaving, Object... params)
- HAVINg ( sql语句 )
- 例: having("sum(age) > 10")—>having sum(age) > 10
- 例: having("sum(age) > {0}", 11)—>having sum(age) > 11
func(Consumerconsumer) func(boolean condition, Consumer consumer)
- func 方法(主要方便在出现if…else下调用不同方法能不断链)
- 例: func(i -> if(true) {i.eq("id", 1)} else {i.ne("id", 1)})
or() or(boolean condition)
-
拼接 OR
注意事项:
主动调用or表示紧接着下一个方法不是用and连接!(不调用or则默认为使用and连接)
-
例: eq("id",1).or().eq("name","老王")—>id = 1 or name = '老王'
or(Consumer consumer) or(boolean condition, Consumer consumer)
- OR 嵌套
- 例: or(i -> i.eq("name", "李白").ne("status", "活着"))—>or (name = '李白' and status <> '活着')
and(Consumer consumer) and(boolean condition, Consumer consumer)
- AND 嵌套
- 例: and(i -> i.eq("name", "李白").ne("status", "活着"))—>and (name = '李白' and status <> '活着')
nested(Consumer consumer) nested(boolean condition, Consumer consumer)
- 正常嵌套 不带 AND 或者 OR
- 例: nested(i -> i.eq("name", "李白").ne("status", "活着"))—>(name = '李白' and status <> '活着')
apply(String applySql, Object... params) apply(boolean condition, String applySql, Object... params)
-
拼接 sql
注意事项:
该方法可用于数据库函数 动态入参的params对应前面applySql内部的{index}部分.这样是不会有sql注入风险的,反之会有!
-
例: apply("id = 1")—>id = 1
-
例: apply("date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")—>date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")
-
例: apply("date_format(dateColumn,'%Y-%m-%d') = {0}", "2008-08-08")—>date_format(dateColumn,'%Y-%m-%d') = '2008-08-08'")
last(String lastSql) last(boolean condition, String lastSql)
-
无视优化规则直接拼接到 sql 的最后
注意事项:
只能调用一次,多次调用以最后一次为准 有sql注入的风险,请谨慎使用
-
例: last("limit 1")
exists(String existsSql) exists(boolean condition, String existsSql)
- 拼接 EXISTS ( sql语句 )
- 例: exists("select id from table where age = 1")—>exists (select id from table where age = 1)
notExists(String notExistsSql) notExists(boolean condition, String notExistsSql)
- 拼接 NOT EXISTS ( sql语句 )
- 例: notExists("select id from table where age = 1")—>not exists (select id from table where age = 1)
2.2.2.1 select说明:
继承自 AbstractWrapper ,自身的内部属性 entity 也用于生成 where 条件及 LambdaQueryWrapper, 可以通过 new QueryWrapper().lambda() 方法获取
select(String... sqlSelect) select(Predicatepredicate) select(Class entityClass, Predicate predicate)
-
设置查询字段
说明:
以上方法分为两类.
第二类方法为:过滤查询字段(主键除外),入参不包含 class 的调用前需要wrapper内的entity属性有值! 这两类方法重复调用以最后一次为准 -
例: select("id", "name", "age")
-
例: select(i -> i.getProperty().startsWith("test"))
2.2.3.1 set说明:
继承自 AbstractWrapper ,自身的内部属性 entity 也用于生成 where 条件及 LambdaUpdateWrapper, 可以通过 new UpdateWrapper().lambda() 方法获取!
set(String column, Object val) set(boolean condition, String column, Object val)
- SQL SET 字段
- 例: set("name", "老李头")
- 例: set("name", "")—>数据库字段值变为空字符串
- 例: set("name", null)—>数据库字段值变为null
setSql(String sql)
- 设置 SET 部分 SQL
- 例: setSql("name = '老李头'")
- 获取 LambdaWrapper
用注解注意事项:
需要mybatis-plus版本 >= 3.0.7 param 参数名要么叫ew,要么加上注解@Param(Constants.WRAPPER) 使用${ew.customSqlSegment}
不支持 Wrapper 内的entity生成where语句
@Select("select * from mysql_data ${ew.customSqlSegment}")
List getAll(@Param(Constants.WRAPPER) Wrapper wrapper);
用XML
ListgetAll(Wrapper ew);
2.3 主键策略SELECT * FROM mysql_data ${ew.customSqlSegment}
提示
主键生成策略必须使用 INPUT
支持父类定义 @KeySequence 子类继承使用
支持主键类型指定(3.3.0 开始自动识别主键类型)
内置支持:
- DB2KeyGenerator
- H2KeyGenerator
- KingbaseKeyGenerator
- OracleKeyGenerator
- PostgreKeyGenerator
如果内置支持不满足你的需求,可实现 IKeyGenerator 接口来进行扩展.
举个栗子
@KeySequence(value = "SEQ_ORACLE_STRING_KEY", clazz = String.class)
public class YourEntity {
@TableId(value = "ID_STR", type = IdType.INPUT)
private String idStr;
}
2.3.1 Spring-Boot
2.3.1.1 使用配置类
@Bean
public IKeyGenerator keyGenerator() {
return new H2KeyGenerator();
}
2.3.1.2 通过 MybatisPlusPropertiesCustomizer 自定义
@Bean
public MybatisPlusPropertiesCustomizer plusPropertiesCustomizer() {
return plusProperties -> plusProperties.getGlobalConfig().getDbConfig().setKeyGenerator(new H2KeyGenerator());
}
2.3.2 Spring
2.3.2.1 XML 配置
2.3.2.2 注解配置
@Bean
public GlobalConfig globalConfig() {
GlobalConfig conf = new GlobalConfig();
conf.setDbConfig(new GlobalConfig.DbConfig().setKeyGenerator(new H2KeyGenerator()));
return conf;
}
3. 拓展
3.1 逻辑删除
3.1.1 使用方法说明:
只对自动注入的 sql 起效:
- 插入: 不作限制
- 查找: 追加 where 条件过滤掉已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
- 更新: 追加 where 条件防止更新到已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
- 删除: 转变为 更新
例如:
- 删除: update user set deleted=1 where id = 1 and deleted=0
- 查找: select id,name,deleted from user where deleted=0
字段类型支持说明:
- 支持所有数据类型(推荐使用 Integer,Boolean,LocalDateTime)
- 如果数据库字段使用datetime,逻辑未删除值和已删除值支持配置为字符串null,另一个值支持配置为函数来获取值如now()
附录:
- 逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案,但实际就是删除。
- 如果你需要频繁查出来看就不应使用逻辑删除,而是以一个状态去表示。
步骤 1: 配置com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig
- 例: application.yml
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
步骤 2: 实体类字段上加上@TableLogic注解
@TableLogic private Integer deleted;3.1.2 常见问题 如何 insert ?
删除接口自动填充功能失效
- 字段在数据库定义默认值(推荐)
- insert 前自己 set 值
- 使用自动填充功能
3.2 通用枚举 3.2.1 声明通用枚举属性
- 使用 deleteById 方法(推荐)
- 使用 update 方法并: UpdateWrapper.set(column, value)(推荐)
- 使用 update 方法并: UpdateWrapper.setSql("column=value")
- 使用 Sql 注入器 注入 com.baomidou.mybatisplus.extension.injector.methods.LogicDeleteByIdWithFill 并使用(3.5.0版本已废弃,推荐使用deleteById)
方式一: 使用 @EnumValue 注解枚举属性
public enum GradeEnum {
PRIMARY(1, "小学"), SECONDORY(2, "中学"), HIGH(3, "高中");
GradeEnum(int code, String descp) {
this.code = code;
this.descp = descp;
}
@EnumValue//标记数据库存的值是code
private final int code;
//。。。
}
方式二: 枚举属性,实现 IEnum 接口如下:
public enum AgeEnum implements IEnum{ ONE(1, "一岁"), TWO(2, "二岁"), THREE(3, "三岁"); private int value; private String desc; @Override public Integer getValue() { return this.value; } }
实体属性使用枚举类型
public class User {
private String name;
private AgeEnum age;
private GradeEnum grade;
}
3.2.2 如何序列化枚举值为数据库存储值?
3.2.2.1 Jackson
一、重写 toString 方法
springboot
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer(){
return builder -> builder.featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
}
jackson
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
以上两种方式任选其一,然后在枚举中复写 toString 方法即可.
二、注解处理
public enum GradeEnum {
PRIMARY(1, "小学"), SECONDORY(2, "中学"), HIGH(3, "高中");
GradeEnum(int code, String descp) {
this.code = code;
this.descp = descp;
}
@EnumValue
@JsonValue //标记响应json值
private final int code;
}
3.2.2.2 Fastjson
一、重写 toString 方法
全局处理方式
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.WriteEnumUsingToString);
局部处理方式
@JSONField(serialzeFeatures= SerializerFeature.WriteEnumUsingToString)
private UserStatus status;
以上两种方式任选其一,然后在枚举中复写 toString 方法即可.
3.3 字段类型处理器类型处理器,用于 JavaType 与 JdbcType 之间的转换,用于 PreparedStatement 设置参数值和从 ResultSet 或 CallableStatement 中取出一个值,本文讲解 mybatis-plus 内置常用类型处理器如何通过TableField注解快速注入到 mybatis 容器中。
- JSON 字段类型
@Data
@Accessors(chain = true)
@TableName(autoResultMap = true)
public class User {
private Long id;
...
@TableField(typeHandler = JacksonTypeHandler.class)
// @TableField(typeHandler = FastjsonTypeHandler.class)
private OtherInfo otherInfo;
}
该注解对应了 XML 中写法为
3.4 自动填充
原理:
- 实现元对象处理器接口:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
- 注解填充字段 @TableField(.. fill = FieldFill.INSERT) 生成器策略部分也可以配置!
public class User {
// 注意!这里需要标记为填充字段
@TableField(.. fill = FieldFill.INSERT)
private String fillField;
....
}
- 自定义实现类 MyMetaObjectHandler
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
// 或者
this.strictInsertFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
// 或者
this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐)
// 或者
this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
// 或者
this.fillStrategy(metaObject, "updateTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug)
}
}
注意事项:
- 填充原理是直接给entity的属性设置值!!!
- 注解则是指定该属性在对应情况下必有值,如果无值则入库会是null
- MetaObjectHandler提供的默认方法的策略均为:如果属性有值则不覆盖,如果填充值为null则不填充
- 字段必须声明TableField注解,属性fill选择对应策略,该声明告知Mybatis-Plus需要预留注入SQL字段
- 填充处理器MyMetaObjectHandler在 Spring Boot 中需要声明@Component或@Bean注入
- 要想根据注解FieldFill.xxx和字段名以及字段类型来区分必须使用父类的strictInsertFill或者strictUpdateFill方法
- 不需要根据任何来区分可以使用父类的fillStrategy方法
- update(T t,Wrapper updateWrapper)时t不能为空,否则自动填充失效
public enum FieldFill {
DEFAULT,
INSERT,
UPDATE,
INSERT_UPDATE
}
3.5 SQL注入器
注入器配置
全局配置 sqlInjector 用于注入 ISqlInjector 接口的子类,实现自定义方法注入。
参考默认注入器 DefaultSqlInjector
- SQL 自动注入器接口 ISqlInjector
public interface ISqlInjector {
void inspectInject(MapperBuilderAssistant builderAssistant, Class> mapperClass);
}
自定义自己的通用方法可以实现接口 ISqlInjector 也可以继承抽象类 AbstractSqlInjector 注入通用方法 SQL 语句 然后继承 BaseMapper 添加自定义方法,全局配置 sqlInjector 注入 MP 会自动将类所有方法注入到 mybatis 容器中。
3.6 执行SQL分析打印该功能依赖 p6spy 组件,完美的输出打印 SQL 及执行时长 3.1.0 以上版本
- p6spy 依赖引入
Maven:
p6spy p6spy 最新版本
Gradle:
compile group: 'p6spy', name: 'p6spy', version: '最新版本'
- application.yml 配置:
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:h2:mem:test
...
- spy.properties 配置:
#3.2.1以上使用 modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory #3.2.1以下使用或者不配置 #modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory # 自定义日志打印 logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger #日志输出到控制台 appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger # 使用日志系统记录 sql #appender=com.p6spy.engine.spy.appender.Slf4JLogger # 设置 p6spy driver 代理 deregisterdrivers=true # 取消JDBC URL前缀 useprefix=true # 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset. excludecategories=info,debug,result,commit,resultset # 日期格式 dateformat=yyyy-MM-dd HH:mm:ss # 实际驱动可多个 #driverlist=org.h2.Driver # 是否开启慢SQL记录 outagedetection=true # 慢SQL记录标准 2 秒 outagedetectioninterval=2
3.7 数据安全保护注意!
- driver-class-name 为 p6spy 提供的驱动类
- url 前缀为 jdbc:p6spy 跟着冒号为对应数据库连接地址
- 打印出 sql 为 null,在 excludecategories 增加 commit
- 批量操作不打印 sql,去除 excludecategories 中的 batch
- 批量操作打印重复的问题请使用 MybatisPlusLogFactory (3.2.1 新增)
- 该插件有性能损耗,不建议生产环境使用。
该功能为了保护数据库配置及数据安全,在一定的程度上控制开发人员流动导致敏感信息泄露。
- 3.3.2 开始支持
- 配置安全
YML 配置:
// 加密配置 mpw: 开头紧接加密内容( 非数据库配置专用 YML 中其它配置也是可以使用的 )
spring:
datasource:
url: mpw:qRhvCwF4GOqjessEB3G+a5okP+uXXr96wcucn2Pev6Bf1oEMZ1gVpPPhdDmjQqoM
password: mpw:Hzy5iliJbwDHhjLs1L0j6w==
username: mpw:Xb+EgsyuYRXw7U7sBJjBpA==
密钥加密:
// 生成 16 位随机 AES 密钥 String randomKey = AES.generateRandomKey(); // 随机密钥加密 String result = AES.encrypt(data, randomKey);
如何使用:
// Jar 启动参数( idea 设置 Program arguments , 服务器可以设置为启动环境变量 ) --mpw.key=d1104d7c3b616f0b
- 数据安全:
字段加密解密(opens new window)
字段脱敏(opens new window)
注意!
- 加密配置必须以 mpw: 字符串开头
- 随机密钥请负责人妥善保管,当然越少人知道越好。



