MybatisPlus 学习
本文最后更新于:1 年前
MybatisPlus 学习
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 操作智能分析阻断,也可自定义拦截规则,预防误操作
2 快速入门
地址: 快速开始 | MyBatis-Plus (baomidou.com)
使用第三方插件
- 导入依赖
- 研究依赖如何配置
- 代码如何编写
- 提高扩展技术能力
步骤
创建数据库
mybatis_plus
创建user表
DROP TABLE IF EXISTS user; CREATE TABLE user ( id BIGINT(20) NOT NULL COMMENT '主键ID', name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名', age INT(11) NULL DEFAULT NULL COMMENT '年龄', email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱', PRIMARY KEY (id) ); # 插入数据 INSERT INTO user (id, name, age, email) VALUES (1, 'Jone', 18, 'test1@baomidou.com'), (2, 'Jack', 20, 'test2@baomidou.com'), (3, 'Tom', 28, 'test3@baomidou.com'), (4, 'Sandy', 21, 'test4@baomidou.com'), (5, 'Billie', 24, 'test5@baomidou.com');
编写项目, 使用springBoot初始化!
导入依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
说明: 我们使用mybatis-plus可以节省我们大量的代码, 尽量不要同时导入 mybatis 和 mybatis-plus, 可能会产生版本差异!
连接数据库
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver username: root password: root url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=GMT
pojo dao-service-controller
pojo
@Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; }
mapper
// 在对应的Mapper上面继承基本的类 BaseMapper @Repository public interface UserMapper extends BaseMapper<User> { // 所有的CRUD操作都已经编写完成 }
启动类
// 扫描我们的 mapper 文件夹 @MapperScan("com.pnca.mapper") @SpringBootApplication public class MybatisPlusApplication { public static void main(String[] args) { SpringApplication.run(MybatisPlusApplication.class, args); } }
test
@SpringBootTest class MybatisPlusApplicationTests { // 继承了 BaseMapper, 所有的方法都来自于父类 // 我们也可以编写自己的扩展方法 @Resource private UserMapper userMapper; @Test void contextLoads() { // 参数是一个 queryWrapper, 条件构造器 List<User> users = userMapper.selectList(null); users.forEach(System.out::println); } }
3 配置日志
我们所有的sqld现在都是不可见的,我们希望知道它是怎么执行的,所以我们必须要看日志!
# 配置日志 (系统自带的,控制台输出)
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
配置完毕日志之后,后面的学习就需要注意这个自动生成的SQL,你们就会喜欢上MyBatis-Plus !
4 CRUD
4.1 插入操作
Insert 插入
@Test
public void testInsert() {
User user = new User();
user.setName("Daniel");
user.setAge(3);
user.setEmail("daniel@alibaba.com");
int result = userMapper.insert(user); //帮我们自动生成id
System.out.println(result); // 受影响的行数
System.out.println(user); // 发现: id自动回填
}
数据库插入的id默认值为:全局的唯一id
4.2 主键生成策略
默认 ID_WORKER 全局唯一id
分布式系统唯一id生成:https://www.cnblogs.com/haoxinyue/p/5208136.html
雪花算法:
snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯一!
主键自增
我们需要配置主键自增:
实体类字段上
@TableId(type = IdType.AUTO)
数据库字段上一定是自增的
再次测试即可
其余的源码解释
public enum IdType {
AUTO(0), // 数据库id自增
NONE(1), // 未设置主键
INPUT(2), // 手动输入,自己写id
ID_WORKER(3), // 默认的全局唯一id
UUID(4), // 全局唯一id uuid
ID_WORKER_STR(5); // ID_WORKER 字符串表示法
}
4.3 更新操作
//测试更新
@Test
public void testUpdate(){
User user = new User();
// 通过条件自动拼接动态sql
user.setId(6L);
user.setName("关注我的微信公众号");
user.setAge(18);
// 注意: updateById 但是参数是一个 对象
int i = userMapper.updateById(user);
System.out.println(i);
}
所有的sql都是自动帮你动态配置的!
4.4 自动填充
创建时间、修改时间!这些个操作一般都是自动化完成的,我们不希望手动更新!
阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上!而且需要自动化!
方式一:数据库级别(工作中不允许修改数据库)
- 在表中新增字段 create_time,update_time
再次测试插入方法,我们需要先把实体类同步
private Date createTime; private Date updateTime;
- 再次查看更新结果即可
方式二:代码级别
删除数据库中的默认值、更新操作
实体类的字段属性上需要增加注解
//字段添加填充内容 @TableField(fill = FieldFill.INSERT) private LocalDateTime createTime; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime updateTime;
编写处理器来处理这个注解即可
@Log4j2 @Component // 一定不要忘记把处理器加到IOC容器中 public class MyMetaObjectHandler implements MetaObjectHandler { // 插入时的填充策略 @Override public void insertFill(MetaObject metaObject) { log.info("start insert fill........."); this.strictUpdateFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐) this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); } // 更新时的填充策略 @Override public void updateFill(MetaObject metaObject) { log.info("start update fill........."); this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); // 起始版本 3.3.3(推荐) } }
4.5 乐观锁
在面试过程中,我们经常会被问到乐观锁,悲观锁。
- 乐观锁:顾名思义,它总是认为不会出现问题,无论干什么都不去上锁!如果出现了问题,再次更新值测试!
- 悲观锁:顾名思义,它总是认为总是出现问题,无论干什么都上锁!再去操作!
乐观锁实现方式:
取出记录时,获取当前version
更新时,带上这个version
执行更新时, set version = newVersion where version = oldVersion
如果version不对,就更新失败
测试一下MyBatisPlus的插件:
增加 version 字段
我们给实体类增加相应的字段
@Version // 乐观锁 Version 注解 private Integer version;
注册组件, 编写配置类
// 扫描我们的 mapper 文件夹 @MapperScan("com.pnca.mapper") @EnableTransactionManagement @Configuration public class MybatisPlusConfig { /** * 新版 */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return mybatisPlusInterceptor; } }
4.6 查询操作
// 测试查询
@Test
public void testSelectById() {
User user = userMapper.selectById(1L);
System.out.println("查询的用户为: " + user);
}
// 批量查询
@Test
public void testSelectByBatchId() {
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
// 条件查询, 使用map
@Test
public void testSelectByMap() {
HashMap<String, Object> map = new HashMap<>();
// 自定义查询
map.put("name", "Tom");
map.put("age", 28);
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
4.7 分页查询
分页网站频繁使用
- 原始使用limit进行分页
- pageHelper第三方插件
- MybatisPlus内置了分页插件
如何使用?
配置拦截器
// 分页插件 @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); }
直接使用Page对象即可
// 测试分页查询 @Test public void testPage(){ // 参数一: 当前页 // 参数二: 页面大小 // 使用了分页插件之后,所有的分页操作变得简单了 Page<User> page = new Page<>(1,5); userMapper.selectPage(page, null); page.getRecords().forEach(System.out::println); System.out.println(page.getTotal()); }
4.8 删除操作
// 测试删除
@Test
public void testdelete(){
userMapper.deleteById(6L);
}
// 测试批量删除
@Test
public void testdeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1287326823914405893L,1287326823914405894L));
}
//通过map删除
@Test
public void testDeleteByMap(){
HashMap<String, Object> map = new HashMap<>();
map.put("name","KUANG");
userMapper.deleteByMap(map);
}
我们在工作中会遇到一些问题:逻辑删除!
4.9 逻辑删除
物理删除:从数据库中直接移除
逻辑删除:在数据库中没有被移除,而是通过一个变量让他生效!deleted=0 –> deleted=1
管理员可以查看被删除的记录!防止数据的丢失!类似于回收站!
测试:
在数据库表中增加一个deleted字段
实体类中增加属性
@TableLogic // 逻辑删除 private Integer deleted;
配置
// 逻辑删除组件 // 高版本不用配置,直接注解即可 public ISqlInjector sqlInjector(){ return new LogicSqlInjector(); }
global-config: db-config: logic-delete-value: 1 logic-not-delete-value: 0
测试删除
测试查询
以上所有的CRUD操作及其扩展操作,我们必须精通掌握!会大大提高工作效率!
5 性能分析插件
我们在平时的开发中,会遇到一些慢sql。解决方案:测试,druid监控…
作用:性能分析拦截器,用于输出每条SQL语句及其执行时间
MyBatisPlus也提供性能分析插件,如果超过这个时间就停止运行!
导入插件
// SQL执行效率插件 @Bean @Profile({"dev","test"}) public PerformanceInterceptor performanceInterceptor(){ PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setMaxTime(100); //ms 设置sql执行的最大时间,如果超过了则不执行 performanceInterceptor.setFormat(true); // 是否格式化 return performanceInterceptor; }
记住,要在SpringBoot中配置环境为dev或者test环境!
测试使用
// 测试查询 @Test public void testSelectById(){ User user = userMapper.selectById(3); System.out.println(user); }
注意:此插件在 3.2.0 版本被移除,推荐使用第三方扩展,执行 SQL 分析打印。
<!-- https://mvnrepository.com/artifact/p6spy/p6spy --> <dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.8.0</version> </dependency>
6 条件构造器
十分重要:wrapper
我们写一些复杂的sql就可以使用它来代替!
测试1
@Test void contextLoads() { // 查询 name 不为空的用户, 并且邮箱不为空的用户, 年龄大于等于12 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.isNotNull("name").isNotNull("email").ge("age", 12); // 参数是一个 queryWrapper, 条件构造器 List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
测试2
@Test void testEqName() { // 查询名字为 pncalbl QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name", "pncalbl"); // 参数是一个 queryWrapper, 条件构造器 User user = userMapper.selectOne(wrapper); System.out.println(user); }
测试3
@Test void testCount() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.between("age", 2, 20); // 区间 userMapper.selectCount(wrapper); }
测试4
@Test void testLike() { QueryWrapper<User> wrapper = new QueryWrapper<>(); // 左和右 %e%,例如 t% wrapper.notLike("name", "pncalbl") .likeRight("email", "t"); List<Map<String, Object>> maps = userMapper.selectMaps(wrapper); maps.forEach(System.out::println); }
测试5
@Test void testSelectObjects() { QueryWrapper<User> wrapper = new QueryWrapper<>(); // id 在子查询中查出来 wrapper.inSql("id", "select id from user where id < 3"); List<Object> objects = userMapper.selectObjs(wrapper); objects.forEach(System.out::println); }
测试6
@Test void testOrder() { QueryWrapper<User> wrapper = new QueryWrapper<>(); // 通过 id 进行排序 wrapper.orderByDesc("id"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
7 代码生成器
dao、pojo、service、controller都给我自己去编写完成!
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
特别说明:
自定义模板有哪些可用参数?Github (opens new window)AbstractTemplateEngine 类中方法 getObjectMap 返回 objectMap 的所有值都可用。
演示效果图:
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
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.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("jobob");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("密码");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.baomidou.ant");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
使用教程
1 添加依赖
MyBatis-Plus 从 3.0.3
之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:
添加 代码生成器 依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency>
添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency>
注意!如果您选择了非默认引擎,需要在 AutoGenerator 中 设置模板引擎。
AutoGenerator generator = new AutoGenerator(); // set freemarker engine generator.setTemplateEngine(new FreemarkerTemplateEngine()); // set beetl engine generator.setTemplateEngine(new BeetlTemplateEngine()); // set custom engine (reference class is your custom engine class) generator.setTemplateEngine(new CustomTemplateEngine()); // other config ...
2 编写配置
MyBatis-Plus 的代码生成器提供了大量的自定义参数供用户选择,能够满足绝大部分人的使用需求。
配置 GlobalConfig
GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java"); globalConfig.setAuthor("jobob"); globalConfig.setOpen(false);
配置 DataSourceConfig
DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8"); dataSourceConfig.setDriverName("com.mysql.jdbc.Driver"); dataSourceConfig.setUsername("root"); dataSourceConfig.setPassword("password");
3 自定义模板引擎
请继承类 com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine
自定义代码模板
//指定自定义模板路径, 位置:/resources/templates/entity2.java.ftl(或者是.vm) //注意不要带上.ftl(或者是.vm), 会根据使用的模板引擎自动识别 TemplateConfig templateConfig = new TemplateConfig() .setEntity("templates/entity2.java"); AutoGenerator mpg = new AutoGenerator(); //配置自定义模板 mpg.setTemplate(templateConfig);
自定义属性注入
InjectionConfig injectionConfig = new InjectionConfig() { //自定义属性注入:abc //在.ftl(或者是.vm)模板中,通过${cfg.abc}获取属性 @Override public void initMap() { Map<String, Object> map = new HashMap<>(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }; AutoGenerator mpg = new AutoGenerator(); //配置自定义属性注入 mpg.setCfg(injectionConfig);
字段其他信息查询注入
new DataSourceConfig().setDbQuery(new MySqlQuery() {
/**
* 重写父类预留查询自定义字段<br>
* 这里查询的 SQL 对应父类 tableFieldsSql 的查询字段,默认不能满足你的需求请重写它<br>
* 模板中调用: table.fields 获取所有字段信息,
* 然后循环字段获取 field.customMap 从 MAP 中获取注入字段如下 NULL 或者 PRIVILEGES
*/
@Override
public String[] fieldCustom() {
return new String[]{"NULL", "PRIVILEGES"};
}
})
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!