一、MyBatisPlus简介 1. 入门案例 问题导入 MyBatisPlus环境搭建的步骤?
1.1 SpringBoot整合MyBatisPlus入门程序 ①:创建新模块,选择Spring初始化,并配置模块相关基础信息 ②:选择当前模块需要使用的技术集(仅保留JDBC)
③:手动添加MyBatisPlus起步依赖 1 2 3 4 5 6 7 8 9 10 <dependency > <groupId > com.baomidou</groupId > <artifactId > mybatis-plus-boot-starter</artifactId > <version > 3.4.1</version > </dependency > <dependency > <groupId > com.alibaba</groupId > <artifactId > druid</artifactId > <version > 1.1.16</version > </dependency >
注意事项1:由于mp并未被收录到idea的系统内置配置,无法直接选择加入
注意事项2:如果使用Druid数据源,需要导入对应坐标
④:制作实体类与表结构 (类名与表名对应,属性名与字段名对应)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 create database if not exists mybatisplus_db character set utf8;use mybatisplus_db; CREATE TABLE user ( id bigint (20 ) primary key auto_increment, name varchar (32 ) not null , password varchar (32 ) not null , age int (3 ) not null , tel varchar (32 ) not null ); insert into user values (null ,'tom' ,'123456' ,12 ,'12345678910' );insert into user values (null ,'jack' ,'123456' ,8 ,'12345678910' );insert into user values (null ,'jerry' ,'123456' ,15 ,'12345678910' );insert into user values (null ,'tom' ,'123456' ,9 ,'12345678910' );insert into user values (null ,'snake' ,'123456' ,28 ,'12345678910' );insert into user values (null ,'张益达' ,'123456' ,22 ,'12345678910' );insert into user values (null ,'张大炮' ,'123456' ,16 ,'12345678910' );
1 2 3 4 5 6 7 8 public class User { private Long id; private String name; private String password; private Integer age; private String tel; }
⑤:设置Jdbc参数(application.yml ) 1 2 3 4 5 6 7 spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC username: root password: root
⑥:定义数据接口,继承BaseMapper 1 2 3 4 5 6 7 8 9 10 package com.itheima.dao;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.itheima.domain.User;import org.apache.ibatis.annotations.Mapper;@Mapper public interface UserDao extends BaseMapper <User > {}
⑦:测试类中注入dao接口,测试功能 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package com.itheima;import com.itheima.dao.UserDao;import com.itheima.domain.User;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import java.util.List;@SpringBootTest public class Mybatisplus01QuickstartApplicationTests { @Autowired private UserDao userDao; @Test void testGetAll () { List<User> userList = userDao.selectList(null ); System.out.println(userList); } }
2. MyBatisPlus概述 问题导入 通过入门案例制作,MyBatisPlus的优点有哪些?
2.1 MyBatis介绍
2.2 MyBatisPlus特性
二、标准数据层开发 1. MyBatisPlus的CRUD操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 package com.itheima;import com.itheima.dao.UserDao;import com.itheima.domain.User;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import java.util.List;@SpringBootTest class Mybatisplus01QuickstartApplicationTests { @Autowired private UserDao userDao; @Test void testSave () { User user = new User(); user.setName("黑马程序员" ); user.setPassword("itheima" ); user.setAge(12 ); user.setTel("4006184000" ); userDao.insert(user); } @Test void testDelete () { userDao.deleteById(1401856123725713409L ); } @Test void testUpdate () { User user = new User(); user.setId(1L ); user.setName("Tom888" ); user.setPassword("tom888" ); userDao.updateById(user); } @Test void testGetById () { User user = userDao.selectById(2L ); System.out.println(user); } @Test void testGetAll () { List<User> userList = userDao.selectList(null ); System.out.println(userList); } }
2. Lombok插件介绍 问题导入 有什么简单的办法可以自动生成实体类的GET、SET方法?
Lombok,一个Java类库,提供了一组注解,简化POJO实体类开发。
1 2 3 4 5 <dependency > <groupId > org.projectlombok</groupId > <artifactId > lombok</artifactId > <version > 1.18.12</version > </dependency >
常用注解:==@Data==,为当前实体类在编译期设置对应的get/set方法,无参/无参构造方法,toString方法,hashCode方法,equals方法等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package com.itheima.domain;import lombok.*;@Data public class User { private Long id; private String name; private String password; private Integer age; private String tel; }
3. MyBatisPlus分页功能 问题导入 思考一下Mybatis分页插件是如何用的?
3.1 分页功能接口
3.2 MyBatisPlus分页使用 ①:设置分页拦截器作为Spring管理的bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.itheima.config;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;@Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor () { MybatisPlusInterceptor mpInterceptor=new MybatisPlusInterceptor(); mpInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); return mpInterceptor; } }
②:执行分页查询
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Test void testSelectPage () { IPage<User> page=new Page<>(1 ,3 ); userDao.selectPage(page,null ); System.out.println("当前页码值:" +page.getCurrent()); System.out.println("每页显示数:" +page.getSize()); System.out.println("总页数:" +page.getPages()); System.out.println("总条数:" +page.getTotal()); System.out.println("当前页数据:" +page.getRecords()); }
3.3 开启MyBatisPlus日志 1 2 3 4 5 6 7 8 9 10 11 spring: datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC username: root password: root mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
3.4 解决日志打印过多问题 3.4.1 取消初始化spring日志打印
做法:在resources下新建一个logback.xml文件,名称固定,内容如下:
1 2 3 4 <?xml version="1.0" encoding="UTF-8"?> <configuration > </configuration >
关于logback参考播客:https://www.jianshu.com/p/75f9d11ae011
3.4.2 取消SpringBoot启动banner图标
1 2 3 spring: main: banner-mode: off
3.4.3 取消MybatisPlus启动banner图标
1 2 3 4 5 6 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: banner: off
三、DQL编程控制 1. 条件查询方式
MyBatisPlus将书写复杂的SQL查询条件进行了封装,使用编程的形式完成查询条件的组合
1.1 条件查询 1.1.1 方式一:按条件查询 1 2 3 4 5 QueryWrapper<User> qw=new QueryWrapper<>(); qw.lt("age" , 18 ); List<User> userList = userDao.selectList(qw); System.out.println(userList);
1.1.2 方式二:lambda格式按条件查询 1 2 3 4 5 QueryWrapper<User> qw = new QueryWrapper<User>(); qw.lambda().lt(User::getAge, 10 ); List<User> userList = userDao.selectList(qw); System.out.println(userList);
1.1.3 方式三:lambda格式按条件查询(推荐) 1 2 3 4 5 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.lt(User::getAge, 10 ); List<User> userList = userDao.selectList(lqw); System.out.println(userList);
1.2 组合条件 1.2.1 并且关系(and) 1 2 3 4 5 6 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.lt(User::getAge, 30 ).gt(User::getAge, 10 ); List<User> userList = userDao.selectList(lqw); System.out.println(userList);
1.2.2 或者关系(or) 1 2 3 4 5 6 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.lt(User::getAge, 10 ).or().gt(User::getAge, 30 ); List<User> userList = userDao.selectList(lqw); System.out.println(userList);
1.3 NULL值处理 问题导入 如下搜索场景,在多条件查询中,有条件的值为空应该怎么解决?
1.3.1 if语句控制条件追加 1 2 3 4 5 6 7 8 9 10 11 Integer minAge=10 ; Integer maxAge=null ; LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); if (minAge!=null ){ lqw.gt(User::getAge, minAge); } if (maxAge!=null ){ lqw.lt(User::getAge, maxAge); } List<User> userList = userDao.selectList(lqw); userList.forEach(System.out::println);
1.3.2 条件参数控制 1 2 3 4 5 6 7 8 Integer minAge=10 ; Integer maxAge=null ; LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.gt(minAge!=null ,User::getAge, minAge); lqw.lt(maxAge!=null ,User::getAge, maxAge); List<User> userList = userDao.selectList(lqw); userList.forEach(System.out::println);
1.3.3 条件参数控制(链式编程) 1 2 3 4 5 6 7 8 Integer minAge=10 ; Integer maxAge=null ; LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.gt(minAge!=null ,User::getAge, minAge) .lt(maxAge!=null ,User::getAge, maxAge); List<User> userList = userDao.selectList(lqw); userList.forEach(System.out::println);
2. 查询投影-设置【查询字段、分组、分页】 2.1 查询结果包含模型类中部分属性 1 2 3 4 5 6 7 QueryWrapper<User> lqw = new QueryWrapper<User>(); lqw.select("id" , "name" , "age" , "tel" ); List<User> userList = userDao.selectList(lqw); System.out.println(userList);
2.2 查询结果包含模型类中未定义的属性 1 2 3 4 5 QueryWrapper<User> lqw = new QueryWrapper<User>(); lqw.select("count(*) as count, tel" ); lqw.groupBy("tel" ); List<Map<String, Object>> userList = userDao.selectMaps(lqw); System.out.println(userList);
3. 查询条件设定 问题导入 多条件查询有哪些组合?
范围匹配(> 、 = 、between)
模糊匹配(like)
空判定(null)
包含性匹配(in)
分组(group)
排序(order)
……
3.1 查询条件
1 2 3 4 5 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.eq(User::getName, "Jerry" ).eq(User::getPassword, "jerry" ); User loginUser = userDao.selectOne(lqw); System.out.println(loginUser);
购物设定价格区间、户籍设定年龄区间(le ge匹配 或 between匹配)
1 2 3 4 5 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.between(User::getAge, 10 , 30 ); List<User> userList = userDao.selectList(lqw); System.out.println(userList);
1 2 3 4 5 LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.likeLeft(User::getName, "J" ); List<User> userList = userDao.selectList(lqw); System.out.println(userList);
1 2 3 4 5 QueryWrapper<User> qw = new QueryWrapper<User>(); qw.select("gender" ,"count(*) as nums" ); qw.groupBy("gender" ); List<Map<String, Object>> maps = userDao.selectMaps(qw); System.out.println(maps);
3.2 查询API
3.3 练习:MyBatisPlus练习 题目:基于MyBatisPlus_Ex1模块,完成Top5功能的开发。
4. 字段映射与表名映射 问题导入 思考表的字段和实体类的属性不对应,查询会怎么样?
4.1 问题一:表字段与编码属性设计不同步
在模型类属性上方,使用**@TableField**属性注解,通过==value ==属性,设置当前属性对应的数据库表中的字段关系。
4.2 问题二:编码中添加了数据库中未定义的属性
在模型类属性上方,使用**@TableField注解,通过 ==exist==**属性,设置属性在数据库表字段中是否存在,默认为true。此属性无法与value合并使用。
4.3 问题三:采用默认查询开放了更多的字段查看权限
在模型类属性上方,使用**@TableField注解,通过 ==select==**属性:设置该属性是否参与查询。此属性与select()映射配置不冲突。
4.4 问题四:表名与编码开发设计不同步
在模型类 上方,使用**@TableName注解,通过 ==value==**属性,设置当前类对应的数据库表名称。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 @Data @TableName("tbl_user") public class User { private Long id; private String name; @TableField(value = "pwd",select = false) private String password; private Integer age; private String tel; @TableField(exist = false) private Boolean online; }
四、DML编程控制 1. id生成策略控制(Insert) 问题导入 主键生成的策略有哪几种方式?
不同的表应用不同的id生成策略
日志:自增(1,2,3,4,……)
购物订单:特殊规则(FQ23948AK3843)
外卖单:关联地区日期等信息(10 04 20200314 34 91)
关系表:可省略id
……
1.1 id生成策略控制(@TableId注解)
1.2 全局策略配置 1 2 3 4 5 mybatis-plus: global-config: db-config: id-type: assign_id table-prefix: tbl_
id生成策略全局配置
表名前缀全局配置
2. 多记录操作(批量Delete/Select) 问题导入 MyBatisPlus是否支持批量操作?
2.1 按照主键删除多条记录 1 2 3 4 5 6 7 List<Long> list = new ArrayList<>(); list.add(1402551342481838081L ); list.add(1402553134049501186L ); list.add(1402553619611430913L ); userDao.deleteBatchIds(list);
2.2 根据主键查询多条记录 1 2 3 4 5 6 List<Long> list = new ArrayList<>(); list.add(1L ); list.add(3L ); list.add(4L ); userDao.selectBatchIds(list);
3. 逻辑删除(Delete/Update) 问题导入 在实际环境中,如果想删除一条数据,是否会真的从数据库中删除该条数据?
3.1 逻辑删除案例 ①:数据库表中添加逻辑删除标记字段
②:实体类中添加对应字段,并设定当前字段为逻辑删除标记字段 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 package com.itheima.domain;import com.baomidou.mybatisplus.annotation.*;import lombok.Data;@Data public class User { private Long id; @TableLogic private Integer deleted; }
③:配置逻辑删除字面值 1 2 3 4 5 6 7 8 9 10 mybatis-plus: global-config: db-config: table-prefix: tbl_ logic-delete-field: deleted logic-not-delete-value: 0 logic-delete-value: 1
逻辑删除本质:逻辑删除的本质其实是修改操作。如果加了逻辑删除字段,查询数据时也会自动带上逻辑删除字段。
4. 乐观锁(Update) 问题导入 乐观锁主张的思想是什么?
4.1 乐观锁案例 ①:数据库表中添加锁标记字段
②:实体类中添加对应字段,并设定当前字段为逻辑删除标记字段 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 package com.itheima.domain;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableLogic;import com.baomidou.mybatisplus.annotation.Version;import lombok.Data;@Data public class User { private Long id; @Version private Integer version; }
③:配置乐观锁拦截器实现锁机制对应的动态SQL语句拼装 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 package com.itheima.config;import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration public class MpConfig { @Bean public MybatisPlusInterceptor mpInterceptor () { MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor(); mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return mpInterceptor; } }
④:使用乐观锁机制在修改前必须先获取到对应数据的verion方可正常进行 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @Test public void testUpdate () { User user = userDao.selectById(3L ); User user2 = userDao.selectById(3L ); user2.setName("Jock aaa" ); userDao.updateById(user2); user.setName("Jock bbb" ); userDao.updateById(user); }
五、快速开发-代码生成器 问题导入 如果只给一张表的字段信息,能够推演出Domain、Dao层的代码?
1. MyBatisPlus提供模板
2. 工程搭建和基本代码编写
第一步:创建SpringBoot工程,添加代码生成器相关依赖,其他依赖自行添加
1 2 3 4 5 6 7 8 9 10 11 12 13 <dependency > <groupId > com.baomidou</groupId > <artifactId > mybatis-plus-generator</artifactId > <version > 3.4.1</version > </dependency > <dependency > <groupId > org.apache.velocity</groupId > <artifactId > velocity-engine-core</artifactId > <version > 2.3</version > </dependency >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package com.itheima;import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.config.DataSourceConfig;public class Generator { public static void main (String[] args) { AutoGenerator autoGenerator = new AutoGenerator(); DataSourceConfig dataSource = new DataSourceConfig(); dataSource.setDriverName("com.mysql.cj.jdbc.Driver" ); dataSource.setUrl("jdbc:mysql://localhost:3306/mybatisplus_db?serverTimezone=UTC" ); dataSource.setUsername("root" ); dataSource.setPassword("root" ); autoGenerator.setDataSource(dataSource); autoGenerator.execute(); } }
3. 开发者自定义配置
1 2 3 4 5 6 7 8 9 GlobalConfig globalConfig = new GlobalConfig(); globalConfig.setOutputDir(System.getProperty("user.dir" )+"/mybatisplus_04_generator/src/main/java" ); globalConfig.setOpen(false ); globalConfig.setAuthor("黑马程序员" ); globalConfig.setFileOverride(true ); globalConfig.setMapperName("%sDao" ); globalConfig.setIdType(IdType.ASSIGN_ID); autoGenerator.setGlobalConfig(globalConfig);
1 2 3 4 5 6 PackageConfig packageInfo = new PackageConfig(); packageInfo.setParent("com.aaa" ); packageInfo.setEntity("domain" ); packageInfo.setMapper("dao" ); autoGenerator.setPackageInfo(packageInfo);
1 2 3 4 5 6 7 8 9 StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig.setInclude("tbl_user" ); strategyConfig.setTablePrefix("tbl_" ); strategyConfig.setRestControllerStyle(true ); strategyConfig.setVersionFieldName("version" ); strategyConfig.setLogicDeleteFieldName("deleted" ); strategyConfig.setEntityLombokModel(true ); autoGenerator.setStrategy(strategyConfig);