文章目录
MyBatis-plus特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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_plus
-
创建表
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) ); --真实开发环境中还需要这些字段,version(乐观锁),deleted(逻辑删除),gmt_create,gmt_modified
-
插入数据
DELETE FROM user; 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初始化
-
导入依赖
<!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--mybatis-plus starter--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency> <!--代码自动生成器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency> <!--非springboot项目--> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency>
- 说明:我们使用mybatis-plus 可以节省我们大量的代码,尽量不要同时导入mybatis和mybatis-plus因为版本有差异
-
连接数据库,这一步和mybatis相同
# mysql 5 驱动不同 com.mysql.jdbc.Driver # mysql 8 驱动不同 com.mysql.cj.jdbc.Driver . 需要增加时区的配置 serverTimezone=UTC spring.datasource.username=root spring.datasource.password=liuzijia spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
-
传统的方式pojo-dao (连接mybatis,配置mapper.xml文件) -service-controller
-
使用了mybatis-plus之后
-
pojo
@Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email;
-
mapper接口
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.study.pojo.User; import org.springframework.stereotype.Repository; //在对应的mapper上面继承基本的类 BaseMapper @Repository//代表持久层 public interface UserMapper extends BaseMapper<User> { //所有CRUD操作都已经编写完成了 //不需要再配置一大堆文件了 }
- 注意点:需要在主启动类上扫描我们Mapper包下的所有接口
@MapperScan("com.study.mapper")
- 或者直接在mapper接口上加
@Mapper
可以
- 注意点:需要在主启动类上扫描我们Mapper包下的所有接口
-
-
测试
@SpringBootTest class MybatisPlusApplicationTests { //继承了BaseMapper, 所有的方法都来自己父类 //我们也可以编写自己的扩展方法 @Autowired private UserMapper userMapper; @Test void contextLoads() { //参数是一个Wrapper,条件构造器,这里我们先不用 --null //查询全部用户 List<User> users = userMapper.selectList(null); users.forEach(System.out::println); } }
- 注意:被查询的表名需要和要查询的pojo的类名相同
- 或者,实体类名和表名不一样的话,在实体类上加上
@TableName("user") //指定数据库中的表名
-
-
配置日志
-
我们所有的sql是不可见的,我们希望知道他是怎么执行的,所以我们必须看日志
-
配置文件中配置
# 配置日志 (默认控制台输出) mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
CRUD扩展
插入数据
@Test
void testInsert(){
User user = new User();
user.setName("cbc");
user.setAge(3);
user.setEmail("cbcbcbc@qq.com");
// 会帮我们自动生成id
int result = userMapper.insert(user);
System.out.println(result);
System.out.println(user);
}
- 注意点:数据库插入的id默认值为:全局的唯一id
主键生成策略
-
对应数据库中的主键 (uuid、自增id、雪花算法、redis、zookeeper)
-
雪花算法 (snowflake):
- snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心:北京、伤害,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。可以保证几乎全球唯一
- 默认使用的是雪花算法作为主键生成策略
-
主键自增:
- 实体类字段上添加注解
@TableId(type = IdType.AUTO)
- 数据库字段一定要设置为自增
- 实体类字段上添加注解
-
IdType其他参数
public enum IdType { /** * 数据库ID自增 * <p>该类型请确保数据库设置了 ID自增 否则无效</p> */ AUTO(0), /** * 该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT) */ NONE(1), /** * 用户输入ID * <p>该类型可以通过自己注册自动填充插件进行填充</p> */ INPUT(2), /* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */ /** * 分配ID (主键类型为number或string), * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(雪花算法) * * @since 3.3.0 */ ASSIGN_ID(3), /** * 分配UUID (主键类型为 string) * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(UUID.replace("-","")) */ ASSIGN_UUID(4),
更新数据
//测试更新
@Test
void testUpdate(){
User user = new User();
user.setId(2L);
user.setName("cbc");
//注意:updateById()参数是一个对象!
int i = userMapper.updateById(user);
System.out.println(i);
}
- 使用了动态SQL
自动填充
- 创建时间、修改时间一般都是自动化完成的
- 阿里巴巴开发手册:所有的数据库表:gmt_create(创建时间)、gmt_modified(修改时间)几乎所有的表都要配置上,而且需要自动化
方式一:数据库级别
- 工作中不建议使用
- 在表中新增两个字段
create_time
,update_time
,默认值填入CURRENT_TIMESTAMP
- 对
update_time
字段勾选更新选项
方式二:代码级别
-
首先去掉时间的默认值,去掉字段更新选项
-
实体类字段属性上需要增加注解
-
编写处理器来处理这个注解
@Component // 放入IOC容器 public class MyMetaObjectHandler implements MetaObjectHandler { // 插入时的填充策略 @Override public void insertFill(MetaObject metaObject) { // metaObject 包含被填充对象的对象 System.out.println("insertFill start......"); Date date = new Date(); this.strictInsertFill(metaObject, "createTime", Date.class, date); // 推荐使用 this.strictInsertFill(metaObject, "updateTime", Date.class, date); // 对象,字段名,属性类,属性 /*this.setFieldValByName("creatTime", new Date(), metaObject); // 字段名,数据,对象 this.setFieldValByName("updateTime", new Date(), metaObject);*/ } // 更新时的填充策略 @Override public void updateFill(MetaObject metaObject) { System.out.println("updateFill start......"); this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date()); // 推荐使用 //this.setFieldValByName("updateTime", new Date(), metaObject); } }
关于LocalDateTime和Date
-
Date
如果不格式化,打印出的日期可读性差,可以使用SimpleDateFormat
对时间进行格式化,但SimpleDateFormat
是线程不安全的- 当多个线程同时使用相同的
SimpleDateFormat
对象【如用static修饰的SimpleDateFormat
】调用format
方法时,多个线程会同时调用calendar.setTime
方法,可能一个线程刚设置好time值另外的一个线程马上把设置的time值给修改了导致返回的格式化时间可能是错误的
- 当多个线程同时使用相同的
-
LocalDate
// 获取当前年月日 LocalDate localDate = LocalDate.now(); // 构造指定的年月日 LocalDate localDate1 = LocalDate.of(2019, 9, 10); // 获取年、月、日、星期几 int year = localDate.getYear(); int year1 = localDate.get(ChronoField.YEAR); Month month = localDate.getMonth(); int month1 = localDate.get(ChronoField.MONTH_OF_YEAR); int day = localDate.getDayOfMonth(); int day1 = localDate.get(ChronoField.DAY_OF_MONTH); DayOfWeek dayOfWeek = localDate.getDayOfWeek(); int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK);
-
LocalTime
// 只会获取几点几分几秒 LocalTime localTime = LocalTime.of(13, 51, 10); LocalTime localTime1 = LocalTime.now(); // 获取小时 int hour = localTime.getHour(); int hour1 = localTime.get(ChronoField.HOUR_OF_DAY); // 获取分 int minute = localTime.getMinute(); int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR); // 获取秒 int second = localTime.getMinute(); int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE);
-
LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime localDateTime1 = LocalDateTime.of(2019, Month.SEPTEMBER, 10, 14, 46, 56); LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime); LocalDateTime localDateTime3 = localDate.atTime(localTime); LocalDateTime localDateTime4 = localTime.atDate(localDate); // 获取LocalDate LocalDate localDate5 = localDateTime.toLocalDate(); // 获取LocalTime LocalTime localTime6 = localDateTime.toLocalTime();
乐观锁配置
-
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
-
给数据库中增加verison字段
-
实体类中增加对应变量并加上注解
@Version // 乐观锁注解,代表该字段为乐观锁 private Integer version;
-
注册组件
@Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor; }
-
说明:
- 支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
- 整数类型下
newVersion = oldVersion + 1
newVersion
会回写到entity
中- 仅支持
updateById(id)
与update(entity, wrapper)
方法 - 在
update(entity, wrapper)
方法下,wrapper
不能复用!!!
-
测试
@Test // 成功案例 void testLocker() { // 1. 查询用户信息 User user = userMapper.selectById(1L); // 2. 修改用户 user.setName("cbc"); user.setName("123123@qq.com"); // 3. 执行更新操作 userMapper.updateById(user); } @Test // 失败案例 void testLockerFail() { // 线程1 User user = userMapper.selectById(1L); user.setName("cbc"); user.setEmail("123123@qq.com"); // 模拟另外一个线程插队 User user2 = userMapper.selectById(1L); user2.setName("cbcsbsbsb"); user2.setEmail("123123@qq.com"); userMapper.updateById(user2); userMapper.updateById(user); // 如果没有乐观锁就会覆盖插队线程的值 }
查询操作
@Test // 单个查询
void testSelect() {
User user = userMapper.selectById(1L);
System.out.println(user);
}
@Test // 多个查询
void testSelectBatch() {
List<User> users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
@Test // 按条件查询之一:Map查询
void testSelectMap() {
HashMap<String, Object> map = new HashMap<>();
// 自定义要查询的条件
map.put("name", "cbc");
map.put("age", 3);
userMapper.selectByMap(map);
}
分页查询
- 原始的使用
limit
进行分页,或者使用pageHelper等第三方插件进行分页 - mybatis-plus内置了分页插件
使用
-
配置拦截器组件
// 配置分页 @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2)); return interceptor; } // 配置乐观锁 + 分页 @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); // 乐观锁 interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 分页 return interceptor; }
-
直接使用Page对象即可
@Test // 测试分页查询 void testPage() { Page<User> page = new Page<>(1, 5); // 当前页,页面大小:查询第1页,每页5条数据 userMapper.selectPage(page, null); // 查看sql语句可发现本质还是使用limit page.getRecords().forEach(System.out::println); }
删除操作
-
根据id删除记录
@Test // 测试删除 void testDeleteByID() { userMapper.deleteById(1410205195668869122L); } @Test // 批量删除 void testDeleteBatchByID() { userMapper.deleteBatchIds(Arrays.asList(1, 2, 3)); } @Test // Map删除 void testDeleteByMap() { HashMap<String, Object> map = new HashMap<>(); map.put("name", "cbc2b"); userMapper.deleteByMap(map); }
-
我们在工作中会遇到有些问题:逻辑删除
逻辑删除
- 物理删除:从数据库中删除
- 逻辑删除:从数据库中没有删除,而是通过变量来让其失效
deleted = 0 -> deleted = 1
- 类似于回收站,防止数据误丢失和实现管理员查看已删除的记录功能等
使用
-
在数据库中增加一个字段
deleted
-
实体类中增加对应变量并加上注解
@TableLogic // 逻辑删除 private Integer deleted;
-
配置逻辑删除
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)
-
测试
@Test // 先执行逻辑删除 void testDeleteByID() { userMapper.deleteById(1410258255325728769L); // 本质走的是update,更新deleted为1 } @Test // 再执行查询 void testSelect() { User user = userMapper.selectById(1410258255325728769L); // 查询当deleted不为1,所以返回null System.out.println(user); }
性能分析插件
- 我们在平时的开发中,会遇到一些慢SQL,mybatis-plus提供了性能分析插件,如果超过一定的时间就停止运行
使用
-
在MybatisPlus3.2.0后,性能分析插件被移除了,官方推荐使用第三方性能分析插件。需要使用p6spy,导入其依赖
<dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>最新版本</version> </dependency>
-
application.yaml配置
spring: datasource: driver-class-name: com.p6spy.engine.spy.P6SpyDriver url: jdbc:p6spy:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8
-
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
条件构造器
-
Warpper:我们写一些复杂的sql就可以使用它来替代
-
测试
@Test void test1() { // 查询name和邮箱不为null,年龄大于等于12岁的用户 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper .isNotNull("name") .isNotNull("email") .ge("age", 12); // ge大于等于 userMapper.selectList(wrapper).forEach(System.out::println); // 可以和之前的map查询对比一下 } @Test void test2(){ // 按name查询一个用户,如果目标有多个会报错 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.eq("name", "Tom"); System.out.println(userMapper.selectOne(wrapper)); } @Test void test3(){ // 查询20岁到30岁(包含边界)之间的用户数量 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper .between("age", 20, 30); /*.ge("age", 20) .le("age", 30);*/ System.out.println(userMapper.selectCount(wrapper)); } @Test void test4(){ // 模糊查询 QueryWrapper<User> wrapper = new QueryWrapper<>(); // likeLeft和likeRight区别:"%值"和"值%" wrapper.notLike("name", "c"); List<Map<String, Object>> maps = userMapper.selectMaps(wrapper); maps.forEach(System.out::println); } @Test void test5(){ // id在子查询中查询出来 QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.inSql("id", "select id from user where id<3"); List<User> list = userMapper.selectList(wrapper); list.forEach(System.out::println); } @Test void test6(){ // 通过id进行排序 QueryWrapper<User> wrapper = new QueryWrapper<>(); // desc降序,asc升序 wrapper.orderByDesc("id"); List<User> users = userMapper.selectList(wrapper); users.forEach(System.out::println); }
代码自动生成
-
dao、pojo、service、controller都可以自动生成
-
默认模板引擎依赖
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>latest-velocity-version</version> </dependency>
-
生成器配置
// 代码自动生成器 public class AutoCode { public static void main(String[] args) { // 先new一个代码自动生成器对象 AutoGenerator mpg = new AutoGenerator(); // 1. 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); // gc对象可使用链式编程 gc.setAuthor("lzj++"); // 设置作者 gc.setOpen(false); // 是否打开资源管理器 gc.setFileOverride(false); // 是否覆盖之前存在的文件 gc.setServiceName("%sService"); // 去Service的I前缀 gc.setIdType(IdType.ASSIGN_ID); // 设置主键策略 gc.setDateType(DateType.ONLY_DATE); // 设置日期格式 gc.setSwagger2(false); // 是否配置swagger mpg.setGlobalConfig(gc); // 放入全局配置 // 2. 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8"); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("liuzijia"); dsc.setDbType(DbType.MYSQL); // 设置数据库类型 mpg.setDataSource(dsc); // 3. 包的配置 PackageConfig pc = new PackageConfig(); pc.setModuleName("pp"); // 设置模块名 pc.setParent("com.study"); // 设置项目包路径 pc.setEntity("pojo"); // 设置实体类包名 pc.setMapper("mapper"); // 设置mapper包名 pc.setService("service"); // 设置service包名 pc.setController("controller"); // 设置controller包名 mpg.setPackageInfo(pc); // 4. 策略配置 StrategyConfig strategy = new StrategyConfig(); strategy.setInclude("user"); // 设置要映射的表名 String类型可变长参数 strategy.setNaming(NamingStrategy.underline_to_camel); // 设置表名转换 下划线转驼峰 strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 设置列名转换 让数据库中的下划线转成实体类驼峰 strategy.setEntityLombokModel(false); // 是否使用lombok strategy.setLogicDeleteFieldName("deleted"); // 设置逻辑删除字段 // 自动填充策略 TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT); // 插入时填充 TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE); // 插入更新时填充 ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); strategy.setVersionFieldName("version"); // 设置乐观锁字段 strategy.setRestControllerStyle(true); // 开启生成controller strategy.setControllerMappingHyphenStyle(true); // 设置controller映射地址驼峰转下划线 mpg.setStrategy(strategy); mpg.execute(); // 执行代码生成器 } }