• SpringBoot 整合MyBatisPlus


    简介

    MyBatis Plus(也称为MyBatis+)是MyBatis框架的增强版本,MyBatis是一种流行的轻量级Java持久化框架。MyBatis Plus提供了额外的功能,并简化了对MyBatis的使用,使得在Java应用程序中使用数据库更加便捷。

    官方文档:https://baomidou.com/
    Maven仓库地址:https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter

    在这里插入图片描述

    整合步骤

    1. 导入 MyBatisPlus 所需要的依赖
    
    <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.0modelVersion>
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>2.6.5version>
            <relativePath/> 
        parent>
    
        <groupId>com.liminggroupId>
        <artifactId>mybatis-plusartifactId>
        <version>0.0.1-SNAPSHOTversion>
        <name>mybatis-plusname>
        <description>springboot整合mpdescription>
    
        <properties>
            <java.version>1.8java.version>
            <log4j.version>1.2.17log4j.version>
            <druid.version>1.2.8druid.version>
            <mybatisplus.version>3.4.2mybatisplus.version>
        properties>
    
        <dependencies>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <scope>runtimescope>
            dependency>
            
            <dependency>
                <groupId>com.baomidougroupId>
                <artifactId>mybatis-plus-boot-starterartifactId>
                <version>${mybatisplus.version}version>
            dependency>
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druid-spring-boot-starterartifactId>
                <version>${druid.version}version>
            dependency>
            
            <dependency>
                <groupId>log4jgroupId>
                <artifactId>log4jartifactId>
                <version>${log4j.version}version>
            dependency>
            
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <optional>trueoptional>
            dependency>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-devtoolsartifactId>
                <scope>runtimescope>
                <optional>trueoptional>
            dependency>
            
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
        dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                    <configuration>
                        <excludes>
                            <exclude>
                                <groupId>org.projectlombokgroupId>
                                <artifactId>lombokartifactId>
                            exclude>
                        excludes>
                    configuration>
                plugin>
            plugins>
        build>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    2.配置数据库连接信息
    server:
      port: 9000
    #####数据源配置#####
    spring:
      datasource:
        username: root
        password: 123456
        #serverTimezone=UTC解决时区的报错
        url: jdbc:mysql://localhost:3306/db_authority_system?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
        driver-class-name: com.mysql.cj.jdbc.Driver
        type: com.alibaba.druid.pool.DruidDataSource
        #druid 数据源专有配置
        initialSize: 5 #连接池的初始大小
        minIdle: 5 #连接池中最小空闲连接数量
        maxActive: 20 #连接池中最大活跃连接数量
        maxWait: 60000 #获取连接的最大等待时间
        timeBetweenEvictionRunsMillis: 60000 #定期检查连接池中空闲连接的间隔时间
        minEvictableIdleTimeMillis: 300000 #连接池中连接的最小空闲时间
        validationQuery: SELECT 1 FROM DUAL #校验连接是否有效的SQL查询语句
        #连接返回时是否进行测试
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        #是否缓存PreparedStatement
        poolPreparedStatements: true
        filters: stat,wall,log4j
        maxPoolPreparedStatementPerConnectionSize: 20 #每个连接上缓存PreparedStatement的最大数量。
        useGlobalDataSourceStat: true #是否开启全局监控统计功能
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
    #####mybatisplus配置#####
    mybatis-plus:
      #加载映射文件
      mapper-locations: classpath:mapper/*.xml
      #设置别名
      type-aliases-package: com.liming.entity
      #开启驼峰命名
      configuration:
        map-underscore-to-camel-case: true
        # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #####配置日志#####
    logging:
      config: classpath:logback.xml
      #设置日志级别的节点
      level:
        com:
          liming: debug
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    3.MybatisX插件快速生成代码

    首先使用IDEA连接mysql
    在这里插入图片描述
    找到表右键,选择插件的逆向工程选项
    在这里插入图片描述
    编写逆向工程配置信息
    在这里插入图片描述
    在这里插入图片描述

    在这里插入图片描述

    4.MybatisX插件生成代码的模板配置
    • 按照指定目录找到插件模板配置目录 Scratches and Consoles -> Extensions -> MybatisX
    • 这里会提供默认模板: 例如在 1.4.13 提供了模板: default-all,default,mybatis-plus2,mybatis-plus3
    • 如果想重置默认模板, 可以右键点击 MybatisX 目录,选择 Restore Default Extensions 选项
      在这里插入图片描述
      自定义模板内容
    名称含义
    tableClass.fullClassName类的全称(包括包名)
    tableClass.shortClassName类的简称
    tableClass.tableName表名
    tableClass.pkFields表的所有主键字段
    tableClass.allFields表的所有字段
    tableClass.baseFields排除主键和 blob 的所有字段
    tableClass.baseBlobFields排除主键的所有字段
    tableClass.remark表注释

    更多信息大家可以查看官网获取

    4.generator批量生成代码

    pom

    
    <dependency>
       <groupId>com.baomidougroupId>
        <artifactId>mybatis-plus-generatorartifactId>
        <version>3.4.1version>
    dependency>
    
    <dependency>
        <groupId>org.freemarkergroupId>
        <artifactId>freemarkerartifactId>
        <version>2.3.28version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    编写核心模板

    package com.liming.utils;
    
    import com.baomidou.mybatisplus.annotation.DbType;
    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.rules.NamingStrategy;
    import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    
    public class GeneratorCode {
        private static String author ="liming";//作者名称
        private static String outputDir ="D:\\";//生成的位置
        private static String driver ="com.mysql.cj.jdbc.Driver";//驱动,注意版本
        //连接路径,注意修改数据库名称
        private static String url ="jdbc:mysql://localhost:3306/db_authority_system?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
        private static String username ="root";//数据库用户名
        private static String password ="123456";//数据库密码
        private static String tablePrefix ="sys_";//数据库表的前缀,如t_user
        private static String [] tables = {"sys_user","sys_permission","sys_department"};   //生成的表
        private static String parentPackage = "com.liming";//顶级包结构
        private static String mapper = "mapper";//数据访问层包名称
        private static String service = "service";//业务逻辑层包名称
        private static String entity = "entity";//实体层包名称
        private static String controller = "controller";//控制器层包名称
        private static String mapperxml = "mapper";//mapper映射文件包名称
    
        public static void main(String[] args) {
            //1. 全局配置
            GlobalConfig config = new GlobalConfig();
            config.setAuthor(author) // 作者
                    .setOutputDir(outputDir) // 生成路径
                    .setFileOverride(true)  // 文件覆盖
                    .setIdType(IdType.AUTO) // 主键策略
                    .setServiceName("%sService")  // 设置生成的service接口的名字的首字母是否为I,加%s则不生成I
                    .setBaseResultMap(true)    //映射文件中是否生成ResultMap配置
                    .setBaseColumnList(true);  //生成通用sql字段
    
            //2. 数据源配置
            DataSourceConfig dsConfig  = new DataSourceConfig();
            dsConfig.setDbType(DbType.MYSQL)  // 设置数据库类型
                    .setDriverName(driver) //设置驱动
                    .setUrl(url)         //设置连接路径
                    .setUsername(username) //设置用户名
                    .setPassword(password);    //设置密码
    
            //3. 策略配置
            StrategyConfig stConfig = new StrategyConfig();
            stConfig.setCapitalMode(true) //全局大写命名
                    .setNaming(NamingStrategy.underline_to_camel) // 数据库表映射到实体的命名策略
                    .setTablePrefix(tablePrefix) //表前缀
                    .setInclude(tables)  // 生成的表
                    .setEntityLombokModel(true);//支持Lombok
    
            //4. 包名策略配置
            PackageConfig pkConfig = new PackageConfig();
            pkConfig.setParent(parentPackage)//顶级包结构
                    .setMapper(mapper)    //数据访问层
                    .setService(service)   //业务逻辑层
                    .setController(controller) //控制器
                    .setEntity(entity) //实体类
                    .setXml(mapperxml);    //mapper映射文件
    
            //5. 整合配置
            AutoGenerator ag = new AutoGenerator();
            ag.setGlobalConfig(config)
                    .setDataSource(dsConfig)
                    .setStrategy(stConfig)
                    .setPackageInfo(pkConfig)
                    .setTemplateEngine(new FreemarkerTemplateEngine()); // 使用Freemarker引擎模板
            //6. 执行
            ag.execute();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76

    运行

    在这里插入图片描述

    可以看见我们所需的代码已经生成,将文件拷贝到项目中即可

    特别注意

    • 将实体类中属性数据类型为LocalDateLocalDateTime修改成java.util.Date类型
  • 相关阅读:
    ATF源码篇(十):docs文件夹-Components组件(9)
    天津教育杂志天津教育杂志社天津教育编辑部2022年第30期目录
    mmocr的识别模型
    JS高级 之 网络编程 - XHR && Fetch
    一个用于操作Excel文件的.NET开源库
    智慧学习环境移动智能终端零信任安全机制改进方案
    Eureka使用及原理详解
    区块链入门
    Linux 实用命令
    thinkphp withJoin 模式下field 无效
  • 原文地址:https://blog.csdn.net/weixin_46370595/article/details/132737316