一、MybatisPlus的特点
-
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
-
损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作.
二、MybatisPlus的使用
1.引入依赖
<!--引入mp依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
2. 相关的实体类属性注解
// 如果表名和实体类名不一致。
@TableName(value = "真实数据库的表名")
//标记该属性为主键。 value:标记列名和属性名的对应
@TableId(value = "id")
//如果属性和列名不一样
@TableField(value = "真实列名")
3.dao层(Mapper)
BaseMapper接口中提供了单表的所有操作。crud.
继承BaseMapper类
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
4.MybatisPlus的增加
* 主键mp提供相应的生成策略:
* AUTO(0),递增策略,如果使用该策略必须要求数据表的列也是递增。
* NONE(1),
* INPUT(2),没有策略,必须人为的输入id值
* ASSIGN_ID(3), 随机生成一个Long类型的值。该值一定是唯一。而且每次生成都不会相同。算法:雪花算法。 适合分布式主键。
* ASSIGN_UUID(4); 随机产生一个String类型的值。该值也是唯一的。
(1)策略的使用是在实体类的@TableId注解中的type属性
@TableId(value = "id",type = IdType.AUTO)//type:主键策略
mp会把生成的主键值复制给对象。
5.MybatisPlus中的删除
* 实际开发中: 我们的删除可能是逻辑删除。所谓的逻辑删除就是修改功能。把某个列修改以删除的状态值。
* 只对自动注入的 sql 起效:
* 插入: 不作限制---
* 查找: 追加 where 条件过滤掉已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
* 更新: 追加 where 条件防止更新到已删除数据,且使用 wrapper.entity 生成的 where 条件会忽略该字段
* 删除: 转变为 更新
* (1)增加一个逻辑字段: isdeleted 0表示未删除 1表示删除.
* (2)实体类上的字段添加 @TableLogic.
需要在数据库中创建一个逻辑删除列在实体类中创建一个与之对应的逻辑删除的字段
@TableLogic//逻辑删除注解
private String isdeleted;
6.MybatisPlus中的修改
不管是添加还是修改我们在工作时对表的操作都需要由一个时间,添加的的时间,修改的时间,所以我们就需要用到到自动填充功能
* 自动填充功能:
* 在阿里规则中我们的每一张表必须具备的三个字段 id,create_time,update_time.
* 这两个字段要不要自己添加。
*
* (1)在需要自动填充属性上@TableField(fill=)
* (2)创建mp自动填充类
(1)我们在实体类上添加两个注解
@TableField(fill = FieldFill.INSERT)//添加时自动填充
private LocalDateTime gmtcreated;
@TableField(fill = FieldFill.UPDATE)//修改时自动填充
private LocalDateTime gmtupdated;
(2)创建自动填充类
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.strictInsertFill(metaObject, "gmtcreated", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
this.strictInsertFill(metaObject, "gmtcreated", () -> 0, Integer.class);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.strictUpdateFill(metaObject, "gmtupdated", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
}
}
7.MybatisPlus的查询
我们使用查询时通常是跟有条件的查询,根据id,根据其他的各种条件
Wrapper:封装了关于查询的各种条件方法
有三个子类最常用:
QueryWrapper查询条件
UpdateWrapper修改条件
LambdaQueryWrapper查询使用lambda表达式条件
QueryWrapper<User> wrapper=new QueryWrapper<>();
//什么都不加就是查全部
/*wrapper.eq("name","李四");//equals类似*/
/* wrapper.ge("age",15);//gt大于等于,lt小于等于*/
/* wrapper.between("age",15,20);//在什么之间*/
/* wrapper.like("name","李");//like模糊查询right:右模糊,left:左模糊*/
wrapper.select("name","email");//只查询哪些列
System.out.println(userMapper.selectList(wrapper));
8.MybatisPlus的分页
* (1)添加分页拦截器
* (2)调用分页方法
添加分页拦截器:
@Configuration
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
使用分页:
public void testPage(){
//P page, 分页对象 Page
// @Param("ew") Wrapper<T> queryWrapper
Page<User> page=new Page<>(3,3);
userMapper.selectPage(page,null);//把查询的结果自动封装到Page对象中
System.out.println("总页码:"+page.getPages());
System.out.println("总条数:"+page.getTotal());
System.out.println("当前页记录:"+page.getRecords());
}
多表联查使用分页
/**
* 联表查询 使用mp的分页功能。
*/
@Test
public void testLianbiao(){
// @Param("ew") Wrapper<T> queryWrapper
Page<User> page=new Page<>(1,3);
QueryWrapper<User> wrapper=new QueryWrapper<>();
wrapper.eq("name","刘德华");
IPage<User> users=userMapper.selectUserWithDept(page,wrapper);
System.out.println("总页码:"+page.getPages());
System.out.println("总条数:"+page.getTotal());
System.out.println("当前页记录:"+page.getRecords());
}
<resultMap id="baseMaper" type="com.ykq.entity.User" autoMapping="true">
<id property="id" column="id"/>
<association property="dept" javaType="com.ykq.entity.Dept" autoMapping="true">
<id column="did" property="did"/>
</association>
</resultMap>
<select id="selectUserWithDept" resultMap="baseMaper">
select * from user u join tbl_dept d on u.did=d.did where isdeleted=0
<if test="ew!=null">
and ${ew.sqlSegment}
</if>
</select>
9.MybatisPlus代码生成器
(1)依赖
<!--代码生成器-->
<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>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
(2)创建代码生成器的配置类
package com.gsh.system.config;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir("./src/main/java");
gc.setAuthor("gsh");
gc.setOpen(false);
gc.setSwagger2(true); //实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mp?serverTimezone=Asia/Shanghai");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("system");
pc.setParent("com.gsh");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return "./src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// 写于父类中的公共字段
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}