0
点赞
收藏
分享

微信扫一扫

Java的MybatisPlus

Part1:MybatisPlus是什么

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

 

Part2:MybatisPlus框架结构

(下图来源于官网)

Java的MybatisPlus_类对象

 

 

 

 

Part3:MybatisPlus可以做什么

即使你没有使用或学习过 Mybatis,也没关系。这不会妨碍你对 MybatisPlus 的学习,使用过后你会感受到它的强大之处,它帮我们简化了很多代码的逻辑。

以下是我使用 MybatisPlus 过程中发现的一些强大特性。

 

1.自动填充功能

实现元对象处理器接口:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler,这样我们就可以对指定字段进行填充入库。

 

2.分页插件

在配置类里面用 Bean 来注入一个方法返回 PaginationInterceptor这个类对象。这样就可以非常容易的实现分页功能。

 

3.乐观锁插件

在配置类里面用 Bean 来注入一个方法返回 OptimisticLockerInterceptor 这个类对象。这样我们就可以解决丢失更新的问题。

 

4.逻辑删除插件

在配置类里面用 Bean 来注入一个方法返回 ISqlInjector 这个类对象。这样我们就可以实现逻辑删除的逻辑。

 

5.执行性能分析插件

在配置类里面用 Bean 来注入一个方法返回 PerformanceInterceptor这个类对象。这样我们可以通过设置参数:maxTime,sql 执行最大时长,超过自动停止运行,有助于发现问题。

 

6.复杂条件查询

通过创建 QueryWrapper 类对象,可以去构建我们想要的不同查询条件的组合,快速的实现各种复杂查询条件的生成。

 

Part4:示例代码

以下是代码结构示意图:

Java的MybatisPlus_类对象_02

 

 

 

 

Step1: User表的字段数据及实体类定义的代码

字段及数据

Java的MybatisPlus_类对象_03

 

实体类代码

 Java的MybatisPlus_类对象_04

 

 

 

Step2: 配置类

@EnableTransactionManagement
@Configuration
@MapperScan("com.test.mpdemo0112.mapper")//在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹
public class MybatisPlusConfig {
//乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
//分页插件
@Bean
public PaginationInterceptor paginationInterceptor(){
return new PaginationInterceptor();
}
//逻辑删除插件
@Bean
public ISqlInjector iSqlInjector(){
return new LogicSqlInjector();
}
//SQL 执行性能分析插件
//(1)参数说明
//参数:maxTime:SQL 执行最大时长,超过自动停止运行,有助于发现问题。
//参数:format:SQL是否格式化,默认false
@Bean
@Profile({"test","dev"})
public PerformanceInterceptor performanceInterceptor(){
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
performanceInterceptor.setMaxTime(500);//ms,超过此处设置的ms则sql不执行
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
}

 

Step3: 元数据对象处理类

 Java的MybatisPlus_类对象_05

 

 

 

Step4: UserMapper继承BaseMapper后获取的mp超能力

 Java的MybatisPlus_python_06

 

 

 

Step5: main入口代码

 Java的MybatisPlus_python_07

 

 

 

Step6: 配置文件的设置

application.properties里面指定了使用哪个环境的配置文件。

 Java的MybatisPlus_python_08

 

 

 

Step7: 测试类

Java的MybatisPlus_sql_09

 

 

 

 

微信搜索公众号:“无量测试之道”,或扫描下方二维码:

 Java的MybatisPlus_sql_10

举报

相关推荐

0 条评论