MybatisPlus
简介
Mybatis- Plus(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD (创建:Create, 读取:Read,更新:Update,删除: Delete),性能基本无损耗,直接面向对象操作,BaseMapper
- 强大的 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
快速入门
1.创建数据库
2.创建表
3.编写项目,初始化项目!使用springBoot初始化!
在group会自动创建包,java Version选择java版本
点击Web-Spring Web
4.导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>mybatis-plus</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis_plus</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
<scope>runtime</scope>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
使用mybatis-plus可以节省大量的代码,尽量不要同时导入mybatis与mybatis-plus!版本的差异!
5.连接数据库
#数据库连接配置
spring.datasource.username=root
spring.datasource.password=x5
spring.datasource.url=jdbc:mysql://localhost:3306/db_wj?useSSL=false&useUnicode=true&characterEncoding=utf8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
6.传统:pojo-dao(连接mybatis,配置mapper.xml文件)-service-controller
使用mybatis-plus: pojo
package com.wj.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.Version;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Wares {
/**
* @Data: 注在类上,提供类的get、set、equals、hashCode、canEqual、toString方法
* @AllArgsConstructor : 注在类上,提供类的全参构造
* @NoArgsConstructor : 注在类上,提供类的无参构造
*/
//对应数据库中的主键(uuid,自增id,雪花算法,zookeepeer,redis)
@TableId(type = IdType.AUTO)
private Long id;
private String wname;
private String type;
private String price;
private String inventory;
private String jianjie;
@Version //乐观锁Version注解
private Integer version;
@TableLogic //逻辑删除
private Integer deleted;
}
mapper接口
package com.wj.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wj.pojo.Wares;
import org.springframework.stereotype.Repository;
//在对应的Mapper上面实现基本的类BaseMapper
@Repository
public interface UserMapper extends BaseMapper <Wares> {
}
使用在测试类中测试
@SpringBootTest
class MybatisPlusApplicationTests {
//继承BaseMapper
@Resource
private UserMapper userMapper;
@Test
void contextLoads() {
List<Wares> list=userMapper.selectList(null);
list.forEach(System.out::println);
}
配置日志
所有的sql现在是不可见的,我们希望知道它是怎么执行的,所以我们必须看日志!
#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
CRUD扩展
insert插入
@Test
public void testInsert(){
Wares w1=new Wares();
w1.setWname("水");
w1.setType("白开水");
w1.setPrice("2");
w1.setInventory("100");
w1.setJianjie("解渴");
int result=userMapper.insert(w1);
System.out.println(result);
System.out.println(w1);
}
主键生成策略
雪花算法(snowflake)
snowflake是Twitter开源的分布式ID生成算法。1.第一位 占用1bit,其值始终是0,没有实际作用。 2.时间戳 占用41bit,精确到毫秒,总共可以容纳约69年的时间。 3.工作机器id 占用10bit,其中高位5bit是数据中心ID,低位5bit是工作节点ID,做多可以容纳1024个节点。 4.序列号 占用12bit,每个节点每毫秒0开始不断累加,最多可以累加到4095,一共可以产生4096个ID。
主键自增
需要配置主键自增
1.实体类字段上@TableId(type=IdType.AUTO)
@TableId(type = IdType.AUTO)
2.数据库字段自增
3.源码解释
public enum IdType {
AUTO, //数据库id自增
NONE, //未设置主键
INPUT, //手动输入
ID_WORKER, //默认的全局唯一id
UUID, //全局唯一id uuid
ID_WORKER_STR; //ID_WORKER 字符串表示法
更新操作
@Test
public void testUpdate(){
Wares w1=new Wares();
w1.setId(1L );
w1.setType("苏打水");
w1.setPrice("1");
int result=userMapper.updateById(w1);
System.out.println(result);
}
自动填充
常见时间,修改时间这些操作一遍都是自动化完成,我们不希望手动进行
阿里巴巴开发手册:所有的数据库表:gmt_create,gmt_modified几乎所有的表都要配置上!而且需要自动化
方式一:数据库级别
在表中新增字段create_time(新增时间),update_time(更新时间)
方式二:代码级别
1.删除数据库的默认值,更新操作!
2.实体类属性上需要增加注解
@TableField(fill= FieldFill.INSERT) //在插入时更新
@@TableField(fill= FieldFill.INSERT_UPDATE) //在插入更新时更新
@TableField(fill = FieldFill.INSERT)
private Data create_Time;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Data update_Time;
3.编写处理器来处理这个注解
@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("create_Time",new Date(),metaObject);
this.setFieldValByName("update_Time",new Date(),metaObject);
}
//更新时的填充策略
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill.....");
this.setFieldValByName("update_Time",new Date(),metaObject);
}
}
乐观锁
乐观锁实现方式:
- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
//测试乐观锁成功
@Test
public void testOptimisticLocker(){
Wares w1=userMapper.selectById(1L);
w1.setType("白开水");
w1.setPrice("1");
userMapper.updateById(w1);
}
1.给数据库增加version字段
2.实体类加相应的字段
@Version //乐观锁Version注解
private Integer version;
@version //乐观锁Version注解
3.注册组件
package com.wj.config;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement //自动管理事务
@MapperScan("com.wj.mapper")
@Configuration //配置类
public class MyBatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
查询操作
//测试批量查询
@Test
public void testSelectById(){
List <Wares> w1= userMapper.selectBatchIds(Arrays.asList(1,2,3));
w1.forEach(System.out::println);
}
//测试条件查询
@Test
public void testSelectByBatchIds(){
HashMap<String,Object> map=new HashMap<>();
map.put("type","白开水");
List<Wares> w1=userMapper.selectByMap(map);
w1.forEach(System.out::println);
}
分页查询
1.原始的limit进行分页
2.pageHelper第三方插件
3MyBatis-Plus内置了分页插件
如何使用!
1.配置拦截器组件即可
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
2.直接使用Page对象
//测试分页查询
@Test
public void testPage(){
Page <Wares> page=new Page<>(1,3);
userMapper.selectPage(page,null);
page.getRecords().forEach(System.out::println);
}
删除操作
逻辑删除
1.在数据表中增加一个字段deleted
2.实体类中增加属性
@TableLogic //逻辑删除
private Integer deleted;
3.配置
//逻辑删除
@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
4.测试类测试
//测试删除
@Test
public void testdelete(){
userMapper.deleteById(2L);
}
性能分析插件
MyBatis-plus也提供性能分析插件,如果超过这个时间就停止运行!
1.导入插件
/**
* SQL执行效率插件
*/
@Bean
@Profile({"dev","test"})
public PerformanceInterceptor performanceInterceptor(){
return new PerformanceInterceptor();
}
要在Springboot中application.properties配置环境为dev 或者 test 环境
#设置开发环境
spring.profiles.active=dev
2.测试使用!
条件构造器
写一些复杂的sql可以使用它替代
package com.example.mybatis_plus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wj.mapper.UserMapper;
import com.wj.pojo.Wares;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.List;
@SpringBootTest
public class WrapperTest {
@Resource
private UserMapper userMapper;
@Test
void contextLoads() {
QueryWrapper<Wares> wrapper =new QueryWrapper<>();
wrapper.isNotNull("price")
.isNotNull("type")
.ge("inventory",100);
userMapper.selectList(wrapper);
}
@Test
public void test2(){
QueryWrapper<Wares> wrapper =new QueryWrapper<>();
wrapper.eq("wname","红茶");
userMapper.selectOne(wrapper);
}
}
代码自动生成器
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
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.setFileOverride(false);//是否覆盖
gc.setServiceName("%sService");//服务的名字,去Service的I前缀
gc.setIdType(IdType.ID_WORKER);
gc.DateType(DateType.ONLY_DATE);
gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
//数据源配置
DataSourceConfig dsc=new DataSourceConfig();
dsc.url("jdbc:mysql://localhost:3306/db_wj?useSSL=false&useUnicode=true&characterEncoding=utf8");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUserName("root");
dsc.setPassword("x5");
dsc.setDbType(Dbtype.MYSQL);
mpg.setDataSource(dsc);
//包的配置
PackageConfig pc=new PackageConfig();
pc.setMouldeName("blog");//模块
pc.setParent("com.wj");//包名
pc.setEntity("entity");//实体类名
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//策略配置
StrategyConfig strategy = new StrategyConfig();
sttrategy.setInclude("user");//设置要映射的表名 strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);//自动lombok
strategy.setRestControllerStyle(true);
strategy.setLogicDeleteFieldName("deleted");//逻辑删除
//自动填充配置
TableFill gmt_create=new TableFill("gmt_create",FieldFill.INSERT);
ArrayList<TableFill> list=new ArrayList();
list.add(gmt_create);
strategy.setTableFillList(list);
//乐观锁
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);//localhost:8080/hello_id_2
mpg.setStrategy();
mpg.execute();//执行