MyBatis-Plus
简介
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
Quick Start
1、导入依赖
<!--connector-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
2、创建实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
private long id;
private String name;
private long age;
private String email;
}
3、创建mapper接口
@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
}
4、连接数据库配置文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?userSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
username: root
password: 1234
5、测试
@Autowired
private UserMapper userMapper;
@Test
void contextLoads() {
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
}
配置日志
打开日志可以看见sql是怎么执行的,使用自带的日志
#日志配置
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
雪花算法
实体类@TableId
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
//对应数据库中的主键
@TableId(type = IdType.AUTO)
private long id;
private String name;
private long age;
private String email;
}
源码分析
public enum IdType {
AUTO(0), //数据库id自增
NONE(1), //未设置主键
INPUT(2), //手动输入
ASSIGN_ID(3),
ASSIGN_UUID(4),
ID_WORKER(3),//默认的全局唯一id
ID_WORKER_STR(3), //ID_WORKER字符串表示
UUID(4); //全局唯一id uuid
}
CURD
查询
查询全部
//1、查询全部
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
批量查询selectBatchIds
List<User> list = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));
list.forEach(System.out::println);
按条件查询,使用map
HashMap<String, Object> map = new HashMap<>();
//定义查询的值
map.put("name", "wangjian");
map.put("age", 20);
List<User> list = userMapper.selectByMap(map);
list.forEach(System.out::println);
增加
//2、增加一个用户
User user = new User();
user.setName("dragon");
user.setAge(20);
user.setEmail("2390721223@qq.com");
//增加一个角色
int insert = userMapper.insert(user);
Date自动填充
创建时间、更新时间这些操作都是自动化完成的!
阿里巴巴开发手册:所有的数据库表:gmt_create、gmt_modified几乎所有的表都要配置上,而且需要自动化!
方式一:数据库级别
在数据库表中添加两个字段create_time、update_time
分别属性设置datetime,timestamp
默认设置为CURRENT_TIMESTAMP,CURRENT_TIMESTAMP
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-isKOzyt1-1652586623336)(C:/Users/hasee/AppData/Roaming/Typora/typora-user-images/image-20201130164250146.png)]
给需要实时更新时间的列设置
ALTER TABLE `user`
MODIFY COLUMN `update_time` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
方式二:代码级别
1、清空数据库刚才设置的值
2、给实体类中的字段添加注解
//设置插入时自动填充
@TableField(fill = FieldFill.INSERT)
private Date createTime;
//设置插入时自动填充,并且修改时自动修改时间
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
3、编写处理器处理上边的注解
package com.dragon.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.time.LocalDateTime;
import java.util.Date;
@Slf4j
@Component //添加到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {
//插入时的填充策略
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill .....");
// strictInsertFill(MetaObject metaObject, String fieldName, Class<T> fieldType, Object fieldVal)
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
//更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill .....");
this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
}
}
4、测试就ok
乐观锁
乐观锁假设数据一般情况下不会造成冲突,所以在数据进行提交更新的时候,才会正式对数据的冲突与否进行检测,如果发现冲突了,则返回给用户错误的信息,让用户决定如何去做。乐观锁适用于读操作多的场景,这样可以提高程序的吞吐量。
乐观锁实现方式:
- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时,set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
1、给数据库增加version字段!
2、实体类增加对应的字段
@Version //乐观锁version注解
private Integer version;
3、注册乐观锁插件
@Configuration
@EnableTransactionManagement
public class MyBatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor() {
return new OptimisticLockerInterceptor();
}
}
4、测试乐观锁多线程下
//测试乐观锁,多线程下
//线程1
User user = userMapper.selectById(1);
user.setName("dragon");
user.setEmail("111111111111@dsd");
//模拟另外一个线程插队
User user2 = userMapper.selectById(1);
user2.setName("dragon2");
user2.setEmail("222222222222@dsd");
userMapper.updateById(user2);
userMapper.updateById(user); //如果没有乐观锁,就会覆盖插队线程的值
分页查询
PaginationInnerInterceptor插件类
1、直接在分页插件到容器中
//分页
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
2、测试:使用Page对象
//分页查询
//参数一:当前页
//参数一:页面大小
Page<User> page = new Page<>(1,2);
Page<User> userPage = userMapper.selectPage(page, null);
userPage.getRecords().forEach(System.out::println);
逻辑删除
**物理删除:**从数据库中直接移除
**逻辑删除:**在数据库中没有被移除,而是通过一个变量让它失效。deleted=0 ----> deleted=1
这样管理员可以查看删除的记录!防止数据的丢失。
1、在数据库中增加一个字段deleted,默认值0
2、实体类增加属性
@TableLogic //逻辑删除
private Integer deleted;
3、配置文件
#配置逻辑删除
mybatis-plus:
global-config:
db-config:
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
4、测试
userMapper.deleteById(6);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JC6C9RZp-1652586623338)(C:/Users/hasee/AppData/Roaming/Typora/typora-user-images/image-20201201120848655.png)]
查看走的是更新,不是删除
查询一下试试
userMapper.selectById(6);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9gSKjReU-1652586623340)(C:/Users/hasee/AppData/Roaming/Typora/typora-user-images/image-20201201120939517.png)]
发现没有查询到语句,会自动过滤被逻辑删除的字段
性能查询插件
我们在平时的开发中,会遇到一些慢sql。
作用:性能分析拦截器,用于输出每条sql语句及其执行时间
MP也提供性能分析插件,如果超过这个时间就停止运行!
条件构造器 QueryWrapper<>
官网全部操作:https://baomidou.com/guide/wrapper.html#abstractwrapper
测试
//查询name不为空,年龄大于20的
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.isNotNull("name")
.ge("age", 20);
List<User> list = userMapper.selectList(wrapper);
list.forEach(System.out::println);
//id在子查询中查出来
QueryWrapper<User> wrapper = new QueryWrapper<>();
//wrapper.inSql("id", "select id from user where id<=3");
wrapper.inSql("id", "1,2,3");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
代码生成器
官网查看https://baomidou.com/guide/generator.html#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B
导入依赖
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!-- 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.2</version>
</dependency>
生成器代码
package com.dragon;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
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 MyCodeGenerator {
public static void main(String[] args) {
//建一个代码自动生成器对象
AutoGenerator autoGenerator = new AutoGenerator();
//1、全局配置
GlobalConfig gc = new GlobalConfig();
String property = System.getProperty("user.dir");
gc.setOutputDir(property + "/src/main/java");
gc.setAuthor("社会你博哥");
gc.setOpen(false);
gc.setFileOverride(false); //是否覆盖
gc.setServiceName("%sService"); //去Service的I前缀
gc.setIdType(IdType.ID_WORKER_STR);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
autoGenerator.setGlobalConfig(gc);
//2.设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?userSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("1234");
dsc.setDbType(DbType.MYSQL);
autoGenerator.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.dragon");
pc.setEntity("pojo");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
autoGenerator.setPackageInfo(pc);
//4、策略配置
StrategyConfig sc = new StrategyConfig();
sc.setInclude("test_table"); //设置要映射的表明
sc.setNaming(NamingStrategy.underline_to_camel);
sc.setColumnNaming(NamingStrategy.underline_to_camel);
sc.setEntityLombokModel(true); //自动lombok
//策略删除配置
sc.setLogicDeleteFieldName("deleted");
//自动填充时间配置
TableFill create_time = new TableFill("create_time", FieldFill.INSERT);
TableFill update_time = new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(create_time);
tableFills.add(update_time);
//添加如策略配置
sc.setTableFillList(tableFills);
//乐观锁配置
sc.setVersionFieldName("version");
sc.setRestControllerStyle(true);
sc.setControllerMappingHyphenStyle(true);
autoGenerator.setStrategy(sc);
//执行
autoGenerator.execute();
}
}