前言:
我们在项目中应用最多的数据持久性框架是mybaits。Mybaits-Plus是一个MyBatis的增强工具,只做增强不做改变。实践证明一些简单的sql完全可以用MP来完成数据的增删改查的操作,作者在项目中也引入了MP,还是很好用的。官网:baomidou.com/。
MyBatisPlus特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作, BaseMapper
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD操作,更有强大的条件构造器,满足各类使用需求,以后简单的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、up date 操作智能分析阻断,也可自定义拦截规则,预防误操作。
MyBatisPlus快速入门
1.创建数据库表
现有一张 User 表,其表结构如下:
数据库sql脚本如下:
DROP TABLE IF EXISTS user;
-- 创建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');
2.初始化工程
创建一个springboot工程:
3.添加依赖
-- springboot其他依赖自行添加
mysql
mysql-connector-java
org.projectlombok
lombok
com.baomidou
mybatis-plus-boot-starter
3.0.5
4.连接数据库
这一步和 mybatis的相关操作相同!
# mysql 5 驱动不同 com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?
useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
5.连接mybatis,配置mapper.xml文件
采用传统的三层结构。同项目中正常的mapper.xml文件的配置,同mybaits。
6.编码
编写实体类 User.java
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
编写 Mapper 包下的 UserMapper接口:
public interface UserMapper extends BaseMapper {
}
7.编写测试类,进行功能测试
@SpringBootTest
public class SampleTestDemo {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
List userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
}
控制台信息:
8.在application.yml中新增配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl //标准输出
CRUD扩展
新增操作
// 测试插入
@Test
public void testInsert(){
User user = new User();
user.setName("苏大强");
user.setAge(22);
user.setEmail("xxxx@qq.com");
int result = userMapper.insert(user); // 帮我们自动生成id
System.out.println(result); // 受影响的行数
System.out.println(user); // 发现,id会自动回填
}
数据库插入的id的默认值为:全局的唯一id。
主键生成策略
默认 ID_WORKER 全局唯一id,我们在项目中需要配置主键自增:
- 实体类字段上 @TableId(type = IdType.AUTO)
- 数据库字段一定要是自增!
- 再次测试插入即可!
MP源码中通过枚举进行主键的配置
public enum IdType {
AUTO(0), // 数据库id自增
NONE(1), // 未设置主键
INPUT(2), // 手动输入
ID_WORKER(3), // 默认的全局唯一id
UUID(4), // 全局唯一id uuid
ID_WORKER_STR(5); //ID_WORKER 字符串表示法
}
更新操作
// 测试更新
@Test
public void testUpdate(){
User user = new User();
// 通过条件自动拼接动态sql
user.setId(2);
user.setName("苏大强就是强");
user.setAge(23);
// 注意:updateById 但是参数是一个 对象!
int i = userMapper.updateById(user);
System.out.println(i);
}
自动填充
创建时间、修改时间!这些个操作一般都是自动化完成的,我们不希望手动更新!
阿里巴巴开发手册中指出:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上!而且需要自动化!
方式一:数据库级别(工作中不允许你修改数据库)
- (1)在表中新增字段 create_time, update_time
- (2)再次测试插入方法,我们需要先把实体类同步!
private Date createTime;
private Date updateTime;
- (3)再次更新查看结果即可
方式二:代码级别
- (1)删除数据库的默认值、更新操作!
- (2)实体类字段属性上需要增加注解
// 字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
- (3)编写处理器来处理这个注解即可!
package com.wang.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
@Slf4j
@Component // 一定不要忘记把处理器加到IOC容器中!
public class MyMetaObjectHandler implements MetaObjectHandler {
// 插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill.....");
// setFieldValByName(String fieldName, Object fieldVal, MetaObject
metaObject
this.setFieldValByName("createTime",new Date(),metaObject);
this.setFieldValByName("updateTime",new Date(),metaObject);
}
// 更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill.....");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
- (4)测试插入
- (5)测试更新、观察时间即可!
乐观锁
乐观锁实现方式:
- 取出记录时,获取当前 version
- 更新时,带上这个version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
乐观锁:1、先查询,获得版本号 version = 1
-- A
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1
-- B 线程抢先完成,这个时候 version = 2,会导致 A 修改失败!
update user set name = "kuangshen", version = version + 1
where id = 2 and version = 1
测试一下MP的乐观锁插件
- 给数据库中增加version字段!
- 我们实体类加对应的字段
@Version //乐观锁Version注解
private Integer version;
- 注册组件
// 扫描我们的 mapper 文件夹
@MapperScan("com.wang.mapper")
@EnableTransactionManagement
@Configuration // 配置类
public class MyBatisPlusConfig {
// 注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
- 测试一下
// 测试乐观锁成功!
@Test
public void testOptimisticLocker(){
// 1、查询用户信息
User user = userMapper.selectById(1L);
// 2、修改用户信息
user.setName("变强");
user.setEmail("1111111111@qq.com");
// 3、执行更新操作
userMapper.updateById(user);
}
// 测试乐观锁失败!多线程下
@Test
public void testOptimisticLocker2(){
// 线程 1
User user = userMapper.selectById(1L);
user.setName("变强111");
user.setEmail("1111111111@qq.com");
// 模拟另外一个线程执行了插队操作
User user2 = userMapper.selectById(1L);
user2.setName("变强222");
user2.setEmail("222222222@qq.com");
userMapper.updateById(user2);
// 自旋锁来多次尝试提交!
userMapper.updateById(user); // 如果没有乐观锁就会覆盖插队线程的值!
}
查询操作
// 测试查询
@Test
public void testSelectById(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
// 测试批量查询!
@Test
public void testSelectByBatchId(){
List users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
users.forEach(System.out::println);
}
// 按条件查询之一使用map操作
@Test
public void testSelectByBatchIds(){
HashMap map = new HashMap<>();
// 自定义要查询
map.put("name","小强");
map.put("age",22);
List users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
分页查询
- 分页在网站使用的十分之多!
- 原始使用 limit 进行分页
- 还有pageHelper 第三方插件
- MP 其实也内置了分页插件!
配置拦截器组件即可
// 分页插件
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
直接使用Page对象:
// 测试分页查询
@Test
public void testPage(){
// 参数一:当前页
// 参数二:页面大小
// 使用了分页插件之后,所有的分页操作也变得简单的!
Page page = new Page<>(2,5);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
删除操作
根据 id 删除记录:
// 测试删除
@Test
public void testDeleteById(){
userMapper.deleteById(1240620674645544965L);
}
// 通过id批量删除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L,124062067464554496
2L));
}
// 通过map删除
@Test
public void testDeleteMap(){
HashMap map = new HashMap<>();
map.put("name","小米su7要变强");
userMapper.deleteByMap(map);
}
逻辑删除
物理删除:从数据库中直接移除。
逻辑删除:再数据库中没有被移除,而是通过一个变量来让他失效! deleted = 0 => deleted = 1。
- 在数据表中增加一个 deleted 字段
- 实体类中增加属性
@TableLogic //逻辑删除
private Integer deleted;
- 配置
// 逻辑删除组件!
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
- 测试删除
在数据库中查看字段的变化,结果发现:记录依旧在数据库,但是值却已经变化了!
// 测试删除
@Test
public void testDeleteById(){
userMapper.deleteById(1240620674645544965L);
}
// 通过id批量删除
@Test
public void testDeleteBatchId(){
userMapper.deleteBatchIds(Arrays.asList(1240620674645544961L,124062067464554496
2L));
}
// 通过map删除
@Test
public void testDeleteMap(){
HashMap map = new HashMap<>();
map.put("name","小新要变强");
userMapper.deleteByMap(map);
}
性能分析插件
我们在平时的开发中,会遇到一些慢sql。性能分析拦截器,用于输出每条 SQL 语句及其执行时间,其中MP也提供性能分析插件,如果超过这个时间就停止运行!
导入插件,要在SpringBoot中配置环境为dev或者 test 环境
/**
* SQL执行效率插件
*/
@Bean
@Profile({"dev","test"})// 设置 dev test 环境开启,保证我们的效率
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new
PerformanceInterceptor();
performanceInterceptor.setMaxTime(100); // ms设置sql执行的最大时间,如果超过了则不
执行
performanceInterceptor.setFormat(true); // 是否格式化代码
return performanceInterceptor;
}
测试使用
@Test
void contextLoads() {
// 参数是一个 Wrapper ,条件构造器,这里我们先不用 null
// 查询全部用户
List users = userMapper.selectList(null);
users.forEach(System.out::println);
}
只要超过了规定的时间就会抛出异常,使用性能分析插件,可以帮助我们提高效率。
条件构造器
写一些复杂的sql就可以使用它来替代。如下
@Test
void contextLoads() {
// 查询name不为空的用户,并且邮箱不为空的用户,年龄大于等于12
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.isNotNull("name").isNotNull("email").ge("age",12);
userMapper.selectList(wrapper).forEach(System.out::println); // 和我们刚才学习的map对比一下
}
@Test
void test2(){
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("name","小新强");
User user = userMapper.selectOne(wrapper); // 查询一个数据,出现多个结果使用List或者 Map
System.out.println(user);
}
//范围查询
@Test
void test3(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.between("age",20,30); // 区间
Integer count = userMapper.selectCount(wrapper);// 查询结果数
System.out.println(count);
}
// 模糊查询
@Test
void test4(){
// 查询年龄在 20 ~ 30 岁之间的用户
QueryWrapper wrapper = new QueryWrapper<>();
// 左和右 t%
wrapper.notLike("name","e").likeRight("email","t");
List
// 子查询
@Test
void test5(){
QueryWrapper wrapper = new QueryWrapper<>();
// id 在子查询中查出来
wrapper.inSql("id","select id from user where id<3");
List
//排序
@Test
void test6(){
QueryWrapper wrapper = new QueryWrapper<>();
// 通过id进行排序
wrapper.orderByAsc("id");
List users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
代码自动生成器
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
导入依赖
com.baomidou
mybatis-plus-generator
3.1.0
测试:
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
// 代码自动生成器
public class HelloCode {
public static void main(String[] args) {
// 需要构建一个 代码自动生成器 对象
AutoGenerator mpg = new AutoGenerator();
// 配置策略
// 1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("狂神说");
gc.setOpen(false);
gc.setFileOverride(false); // 是否覆盖
gc.setServiceName("%sService"); // 去Service的I前缀
gc.setIdType(IdType.ID_WORKER);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//2、设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/kuang_community?
useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.kuang");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("blog_tags","course","links","sys_settings","user_record","user_say"); // 设置要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 自动lombok;
strategy.setLogicDeleteFieldName("deleted");
// 自动填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
ArrayList tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategy.setTableFillList(tableFills);
// 乐观锁
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2
mpg.setStrategy(strategy);
mpg.execute(); //执行
}
}
上面是对Mybaits-plus的用法及功能做了分析,在工作中应用MP会大大提高开发效率。
让我们一起用起来吧~