MyBatisPlus(四)性能分析插件 | 条件构造器 | 代码生成器

2023-05-16

文章目录

    • 一、性能分析插件
      • 1、导入插件
      • 2、 测试使用
    • 二、条件构造器
      • 1、ge、gt、le、It、isNull、isNotNull
      • 2、eq、ne
      • 3、between、notBetween
      • 4、like、noLike、likeLeft、likeRight
      • 5、orderBy、orderByDesc、orderByAsc
      • 6、inSql
      • 7、last
      • 8、指定查询的列
    • 三、代码生成器
      • 1、导入MP 坐标
      • 2、导入数据库配置
      • 3、MyBatisPlusConfig配置类
      • 4、代码生成器类


一、性能分析插件

我们在平时的开发汇总,会遇到一些慢SQL。

作用:性能分析拦截器,用于输出每条SQL语句及其执行时间。

MP也提供了性能分析插件,如果超过这个时间就停止运行。

1、导入插件

// SQL 执行效率插件
@Bean
@Profile({"dev","test"})// 设置 dev、test环境开启,保证我们的效率
public PerformanceInterceptor performanceInterceptor(){
    PerformanceInterceptor performanceInterceptor =new PerformanceInterceptor();
    performanceInterceptor.setMaxTime(100);// ms  设置SQL执行的最大时间,如果超过了则就不执行
    performanceInterceptor.setFormat(true);// 是否格式化代码
    return performanceInterceptor;
}

注意: 要在SprinBoot 中配置环境为 dev 或者 test 环境。

# 设置开发环境 dev、test、prod
spring.profiles.active=dev

2、 测试使用

@Test
void contextLoads() {
    // 查询一个 Wrapper, 条件构造器,这里我们不用null
    // 查询全部用户
    List<User> users = userMapper.selectList(null);
    users.forEach(System.out::println);
}

在这里插入图片描述
使用性能分析插件,可以帮助我们提高效率。

二、条件构造器

十分重要:Wrapper

在这里插入图片描述
Wrapper:条件构造抽象类,最顶端父类

  • AbstractWrapper:用于查询条件封装,生成sql的 where条件
    • QueryWrapper:Entity对象封装操作类,不是用lambda语法
    • UpdateWrapper : Update条件封装,用于Entity对象更新操作
  • AbstractLambdaWrapper:Lambda语法使用Wrapper统一处理解析lambda获取column
    • LambdaQueryWrapper:看名称也能明白就是用于Lambda语法使用的查询Wrapper
    • LambdaUpdateWrapper:Lambda更新封装Wrapper

我们写一些复杂的SQL就可以使用它们来替代。

在这里插入图片描述

1、ge、gt、le、It、isNull、isNotNull

@SpringBootTest
public class WrapperTest {

    @Autowired
    private UserMapper userMapper;

    // 条件查询
    @Test
    void contextLoads() {
        // 查询 name 不为空的用户,并且邮箱不为空的用户,年龄大于等于12
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper
                .isNotNull("name")
                .isNotNull("email")
                .ge("age","12");
        userMapper.selectList(wrapper).forEach(System.out::println);// 和我们学习的 Map 对于以下
    }
}

SQL语句
SELECT id,name,age,email,version,deleted,create_time,update_time
FROM user
WHERE deleted=0
AND name IS NOT NULL
AND email IS NOT NULL
AND age > ‘12’

2、eq、ne

注意:selectOne返回的是一条实体记录,当出现多条记录会报错

// 条件查询
@Test
 public void test2() {
     // 查询名字为 Billie
     QueryWrapper<User> wrapper = new QueryWrapper<>();
     wrapper.eq("name","Billie");
     User user = userMapper.selectOne(wrapper);// 查询一个数据,出现多个结果使用List,或者Map
     System.out.println(user);
 }

SQL语句
SELECT id,name,age,email,version,deleted,create_time,update_time
FROM user
WHERE deleted=0
AND name = ‘Billie’

3、between、notBetween

// 条件查询
@Test
public void test3() {
     // 查询年龄在20 - 30 岁之间的用户
     QueryWrapper<User> wrapper = new QueryWrapper<>();
     wrapper.between("age",20,30);
     Integer count = userMapper.selectCount(wrapper);
     System.out.println(count);
 }

SQL
SELECT COUNT(1)
FROM user
WHERE deleted=0
AND age BETWEEN 20 AND 30

4、like、noLike、likeLeft、likeRight

// 模糊查询
@Test
public void test4() {
    // 查询名字中不包含e,邮箱中以t开头的
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    // 左和右   %a%
    wrapper
            .notLike("name","e")
            .likeRight("email","t");  // t%
    List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
    maps.forEach(System.out::println);
}

SQL语句
SELECT id,name,age,email,version,deleted,create_time,update_time
FROM user
WHERE deleted=0
AND name NOT LIKE ‘%e%’
AND name LIKE ‘t%’

5、orderBy、orderByDesc、orderByAsc

@Test
public void test7() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    // 通过id进行排序
    wrapper.orderByDesc("id");

    List<User> users = userMapper.selectList(wrapper);
    users.forEach(System.out::println);
}

6、inSql

//组合查询
@Test
public void test6() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.inSql("id","select id from user where id <3");

    List<Object> objects = userMapper.selectObjs(wrapper);
    objects.forEach(System.out::println);
}

SQL语句
SELECT id,name,age,email,version,deleted,create_time,update_time
FROM user
WHERE deleted=0
AND id IN(select id from user where id < 3)

7、last

直接拼接到sql的最后

注意:只能调用一次,多次调用以最后一次为准,有sql注入的风险,请谨慎使用

@Test
public void test7() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    // 通过id进行排序
    wrapper.last("limit 1");

    List<User> users = userMapper.selectList(wrapper);
    users.forEach(System.out::println);
}

SQL
SELECT id,name,age,email,version,deleted,create_time,update_time
FROM user WHERE deleted 0 limit 1

8、指定查询的列

@Test
public void test7() {
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    // 通过id进行排序
    wrapper.select("id","name","age");

    List<User> users = userMapper.selectList(wrapper);
    users.forEach(System.out::println);
}

SQL
SELECT id,name,age
FROM user
WHERE deleted=0

三、代码生成器

dao、pojo、service、controller都给我们自己编写完成。

AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。

1、导入MP 坐标

<!--mybatis-plus-->
<dependency>
     <groupId>com.baomidou</groupId>
     <artifactId>mybatis-plus-boot-starter</artifactId>
     <version>3.0.5</version>
 </dependency>

2、导入数据库配置

# 服务端口
server.port=9000
# 设置开发环境
spring.profiles.active=dev
# 禁止模板缓存
spring.thymeleaf.cache=false

# mysql 5 驱动不同 com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/starSea99_community?useSSL=false&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# mysql 8 驱动不同 com.mysql.cj.jdbc.Driver,需要增加时区的配置 serverTimezone=GMT%2B8

# 配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

# 配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

3、MyBatisPlusConfig配置类

// 添加 @MapperScan 注解,扫描 Mapper 文件夹
@MapperScan("com.kuang.mapper")
@EnableTransactionManagement
@Configuration//配置类
public class MyBatisPlusConfig {
    //注册乐观锁插件
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }

    //分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }

    //逻辑删除组件
    @Bean
    public ISqlInjector sqlInjector(){
        return  new LogicSqlInjector();
    }

    // SQL 执行效率插件
    @Bean
    @Profile({"dev","test"})// 设置 dev、test环境开启,保证我们的效率
    public PerformanceInterceptor performanceInterceptor(){
        PerformanceInterceptor performanceInterceptor =new PerformanceInterceptor();
        performanceInterceptor.setMaxTime(1000);// ms  设置SQL执行的最大时间,如果超过了则就不执行
        performanceInterceptor.setFormat(true);// 是否格式化代码
        return performanceInterceptor;
    }
}

4、代码生成器类

//代码生成器
public class KuangCode {

    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("StarSea99");  // 设置作者
        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);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);

        // 包配置
        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);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude("user");// 单个表映射,设置要映射的表名,只需要修改这里
        //strategy.setInclude("blog","blog_tags","course","links","sys_settings","user","user_course","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<TableFill> 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();// 执行
    }
}

部分效果图

在这里插入图片描述


如果有收获!!! 希望老铁们来个三连,点赞、收藏、转发。
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MyBatisPlus(四)性能分析插件 | 条件构造器 | 代码生成器 的相关文章

  • idea mybatisplus 插件使用

    在plugin中安装mybatisplus 插件 使用 配置数据库 生成代码 表新增字段 xff0c 重新生成实体类覆盖 因业务需求 xff0c 表中可能会时不时增加一些字段 xff0c 大多情况下实体类中不会添加表中没有的字段 xff0c
  • 【Java开发】 Mybatis-Plus 04:条件构造器-wrapper

    条件构造器算是Mybatis Plus中很重要的知识点了 xff0c 个人觉得它类似于Service的链式查询 xff0c 将诸多条件集中在一个wrapper中 xff0c 以达到高效便捷的目的 本文也是对01 02 03 内容的整合归纳
  • SpringBoot整合MybatisPlus时“注入失败”的问题记录

    问题情景 xff1a 最近将几个小的Demo整合在一起 xff0c 其中项目A使用Mybatis项目B使用Mybatis plus 在正常的修改完application yml xff0c pom文件后尝试启动项目 xff0c 启动失败 报
  • 引入MybatisPlus与实操

    文章目录 1 MybatisPlus概述2 快速入门2 1 步骤 3 配置日志 1 MybatisPlus概述 特色 特性 无侵入 xff1a 只做增强不做改变 xff0c 引入它不会对现有工程产生影响 xff0c 如丝般顺滑 损耗小 xf
  • mybatis-plus Invalid bound statement (not found):

    1 若是使用了多数据源配置 请检查 DataSourceConfig配置类 将SqlSessionFactoryBean改为mybatis plus里面的MybatisSqlSessionFactoryBean Bean name test
  • mybatis—plus

    接口和实现类都继承 如果你让你的服务接口继承 IService 并让你的服务实现类继承 ServiceImpl 那么你的服务接口将明确地列出所有可用的 CRUD 方法 只继承 ServiceImpl 如果你只让你的服务实现类继承 Servi
  • 【Mybatis-Plus】分页简单使用

    大纲 一 前期准备 1 创建测试表 用户并插入数据 2 导入mybatis plus依赖 3 连接数据库 application yaml 4 生成实体类 5 配置类 二 Mybatis Plus帮助文档分析 三 功能实现 1 总览目录结构
  • @TableField介绍和使用

    1 TableField exist false 注解加载bean属性上 表示当前属性不是数据库的字段 但在项目中必须使用 这样在新增等使用bean的时候 mybatis plus就会忽略这个 不会报错 否则会报一个如下的异常 Error
  • mybatisPlus之getById和selectById查询不出结果

    最终导致查询不出结果的原因可能有多种 我这里说出我遇到的一种原因 希望对你有帮助 我是因为在数据库添加了一个字段 没有及时地更新mapper xml中的resultMap导致的 大晚上的写代码 脑子不太好使 2 最近又遇到了一种情况 我数据
  • mybatisplus 修改某个字段为空值

    文章目录 前言 一 重现bug 二 解决方法 总结 前言 需求 移除企业 将ent id设置为null 一 重现bug 1 使用updateById 更新单独个字段为空值 结果报错 Override public void update S
  • MyBatis-Plus深入 —— 条件构造器与插件管理

    前言 在前面的文章中 荔枝梳理了一个MyBatis Plus的基本使用 配置和通用Service接口 我们发现在MyBatis Plus的辅助增强下我们不再需要通过配置xml文件中的sql语句来实现基本的sql操作了 不愧是最佳搭档 在这篇
  • MybatisPlus QueryWrapper的null查询

    查询字段对应 null的值 特殊 isNull QueryWrapper
  • Maven项目代码生成器插件(code-generator-maven-plugin)

    简介 code generator maven plugin 是一个基于baomidou mybatis plus generator实现的 在 Maven 项目中生成代码的 Maven 插件 主要包括 code generator MyB
  • mybatisPlus-wrapper使用

    创建测试类 import com baomidou mybatisplus core conditions query QueryWrapper import com plus mybatis mapper UserMapper impor
  • MyBatis-Plus:条件构造器Wrapper

    目录 1 Wrapper概述 1 1 Wrapper的继承关系 1 2 Wapper介绍 1 3 各个构造器使用区别 1 4 构造器常用方法 2 Wrapper常用构造器介绍 2 1 QueryWrapper 2 2 UpdateWrapp
  • SpringBoot 中 MyBatis-Plus 集成动态多数据源过程(亲测可用)

    使用场景 当你的项目中使用到多个数据源或者需要在程序运行过程中动态的添加数据源时可以参考本文中的实现 这里使用的是dynamic datasource spring boot starter 它是一个基于springboot的快速集成多数据
  • 服务端架构:Mybatis-Plus的优缺点

    前段时间帮朋友处理java后端架构问题 看到了mybatis plus 其实早几年就知道这个东西 但一直没用没学 这两天许久未见的web服务看了看 聊聊个人感受 如有不适 请见谅 文章目录 优点 缺点 1 对数据访问层DAO的上层入侵太强
  • 2.mybatis-plus入门案例

    2 mybatis plus入门案例 mybatis plus入门案例 2 mybatis plus入门案例 一 创建并初始化数据库 1 创建数据库 2 创建 User 表 二 初始化工程 三 添加依赖 1 引入依赖 2 idea中安装lo
  • 【MyBatis-Plus】之批量插入

    一 应用情景介绍 在实际的项目开发过程中 常常遇到批量保存数据的场景 当数据量比较少 比如只有几条数据的情况下 我们可以使用 for 循环来 insert 数据 但如果数据量比较多的情况下就不行 特别是并发的情况下 因为这样会增加数据库的负
  • Mybatis-Plus insertBatch执行缓慢原因查询

    背景 最近在SpringCloud项目中 使用Mybatis Plus执行一个88万条左右的数据插入MySQL数据库的操作时 发现执行时长竟然长达2个小时 按理讲 MP框架执行如下批处理操作时 XXService insertBatch X

随机推荐

  • SpringCloud(二)入门案例之支付模块与订单模块的调用

    SpringCloud xff08 一 xff09 微服务概述 xff1a https blog csdn net weixin 45606067 article details 108481733 构建SpringCloud工程 概述 x
  • SpringCloud(三)Eureka服务注册中心

    文章目录 1 Eureka基础知识什么是服务治理什么是服务注册Eureka两大组件 2 Eureka介绍及原理理解介绍原理 3 单机版Eureka 构建步骤4 集群版Eureka 构建步骤Eureka集群原理说明EurekaServer集群
  • SpringCloud(四)zookeeper介绍及原理

    SpringCloud xff08 四 xff09 zookeeper介绍及原理 xff1a https blog csdn net weixin 45606067 article details 108499344 Zookeeper服务
  • docker 的安装 - 常用命令 - 应用部署

    文章目录 1 Docker简介什么是虚拟化什么是Docker容器与虚拟化比较Docker 组件1 Docker服务器与客户端2 Docker镜像与容器3 Register xff08 注册中心 xff09 2 Docker安装与启动安装Do
  • SpringCloud(六)Ribbon负载均衡服务调用

    Ribbon负载均衡 概述 是什么 Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端 负载均衡工具 简单的说 xff0c Ribbon是Netflix发布的开源项目 xff0c 主要功能是提供客户端的
  • Python:map()函数使用详解

    1 函数定义 xff1a map function iterable 2 作用 xff1a 该函数通过接收一个函数function作为处理函数 xff0c 然后接收一个参数序列iterable xff0c 并使用处理函数对序列中的每个元素逐
  • SpringCloud(五)Consul服务注册与发现

    SpringCloud xff08 四 xff09 zookeeper介绍及原理 xff1a https blog csdn net weixin 45606067 article details 108538357 Consul简介 是什
  • SpringCloud(七)OpenFeign负载均衡服务调用

    1 概述 1 OpenFeign是什么 官网解释 xff1a https cloud spring io spring cloud static Hoxton SR1 reference htmlsingle spring cloud op
  • Zookeeper概述 | 安装部署(Windows和Linux)

    Zookeeper 一 Zokeeper 门 1 概述 Zookeeper是一个开源的分布式的 xff0c 为分布式应用提供协调服务的Apache项目 ZooKeeper is a centralized service for maint
  • Zookeeper内部原理

    Zookeeper概述 安装部署 xff08 Windows和Linux xff09 xff1a https blog csdn net weixin 45606067 article details 108619378 1 选举机制 面试
  • jsp和servlet的区别

    基本介绍 Servlet xff1a Servlet 是一种服务器端的Java应用程序 xff0c 具有独立于平台和协议的特性 xff0c 可以生成动态的Web页面 它担当客户请求 xff08 Web浏览器或其他HTTP客户程序 xff09
  • Session学习笔记

    1 session 简介 session 是我们 jsp 九大隐含对象的一个对象 session 称作域对象 xff0c 他的作用是保存一些信息 xff0c 而 session 这个域对象是一次会话期间使用同一个对象 所以这个对象可以用来保
  • session和cookie 区别【面试】

    说说Cookie和Session的区别 xff1f 1 存取方式的不同 xff08 Cookie只能保存ASCII xff0c Session可以存任意数据类型 xff09 Cookie中只能保管ASCII字符串 xff0c 假如需求存取U
  • JSP 九大内置对象,四大域对象

    JSP的九大内置对象 内置对象名 类型 request HttpServletRequest response HttpServletResponse session HttpSession application ServletConte
  • SpringCloud(八)Hystrix断路器

    文章目录 1 概述分布式系统面临的问题是什么能干嘛官网资料Hystrix官宣 xff0c 停更进维 2 Hystrix重要概念3 hystrix案例构建项目高并发测试故障现象和导致原因上诉结论如何解决 xff1f 解决的要求服务降级服务熔断
  • 谷粒学院(一)项目介绍

    一 项目背景 在线教育顾名思义 xff0c 是以网络为介质的教学方式 xff0c 通过网络 xff0c 学员与教师即使相隔万里也可以开展教学活动 xff0c 此外 xff0c 借助网络课件 xff0c 学员还可以随时随地进行学习 xff0c
  • PyTorch:Dataset()与Dataloader()的使用详解

    目录 1 Dataset类的使用 2 Dataloader类的使用 3 总结 Dataset类与Dataloader类是PyTorch官方封装的用于在数据集中提取一个batch的训练用数据的接口 xff0c 其实我们也可以自定义获取每个ba
  • MyBatisPlus(二)入门案例

    一 快速入门 使用第三方组件 xff1a 导入对应的依赖研究依赖如何配置代码如何编写提高扩展技术能力 操作步骤 1 创建数据库mybatis plus 2 创建user表 span class token keyword DROP span
  • MyBatisPlus(三)CRUD接口操作

    一 CRUD扩展 Insert 插入 span class token comment 测试插入 span span class token annotation punctuation 64 Test span span class to
  • MyBatisPlus(四)性能分析插件 | 条件构造器 | 代码生成器

    文章目录 一 性能分析插件1 导入插件2 测试使用 二 条件构造器1 ge gt le It isNull isNotNull2 eq ne3 between notBetween4 like noLike likeLeft likeRig