码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis-Plus中的代码生成器AutoGenerator超详细解析!完整配置!

时间:2020-10-31 02:45:44      阅读:25      评论:0      收藏:0      [点我收藏+]

标签:misc   空指针   date   value   cep   增删改   介绍   rest   target   

集成AutoGenerator快速搭建项目

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

面试资料领取只需:?点击这里领取!!!!暗号:51CTO

1. pom.xml 展示

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.gdufs.project</groupId>
    <artifactId>ch3_maven_test</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>

        <!-- myBatis -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.4.0</version>
        </dependency>
        <!-- Junit单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!--Log4J日志工具  打印运行日志用的!-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>

<!--        mybatis generertor-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.30</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.22</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.22</version>
        </dependency>
    </dependencies>

    <!--如果是WEB项目,那么不用创建bulid标签-->
    <build>
        <!--编译的时候同时也把包下面的xml同时编译进去-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <!-- 指定jdk版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>utf-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

2. 代码生成器的java类

package cn.java;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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 com.baomidou.mybatisplus.generator.config.FileOutConfig;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }

    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("蔡诚杰");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql:///university?serverTimezone=Hongkong");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("jimmycai");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模块名"));
        pc.setParent("cn.java");
//        pc.setMapper("mapper");
//        pc.setXml("mapper.xml");
        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 projectPath + "/src/main/java/cn/java/" + pc.getModuleName()
                        + "/mapper/" + 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.no_change);
        strategy.setEntitySerialVersionUID(false);
        strategy.setColumnNaming(NamingStrategy.no_change);
//        strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
//        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(false);
        // 公共父类
//        strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

4. 下面开始介绍不同系列的坑

(1). 坑1 (错误日志)
com.lqf.springbootmybatisplusgenrator.MpGenerator
20:04:10.529 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - 
==========================准备生成文件...==========================
Exception in thread "main" java.lang.NoClassDefFoundError: freemarker/template/Configuration
    at com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine.init(FreemarkerTemplateEngine.java:45)
    at com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine.init(FreemarkerTemplateEngine.java:38)
    at com.baomidou.mybatisplus.generator.AutoGenerator.execute(AutoGenerator.java:98)
    at com.lqf.springbootmybatisplusgenrator.MpGenerator.main(MpGenerator.java:91)
Caused by: java.lang.ClassNotFoundException: freemarker.template.Configuration
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 4 more
复制代码

看上面的错误java.lang.NoClassDefFoundError: freemarker/template/Configuration 问题是找不到freemarker/template/Configuration这是怎么引起的呢

注意: freemarker我们那里用到了 ,看下面的代码

 focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return rb.getString("OutputDirXml") + "/mapper/" + rb.getString("className") + "/" + tableInfo.getEntityName() + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
复制代码

我们在使用new FileOutConfig("/templates/mapper.xml.ftl") 生成模板的时候是需要依赖freemarker包所以我们需要在pom文件中引入

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
(2). 坑2

字段类型为 bit、tinyint(1) 时映射为 boolean 类型这个时候MyBatis 是不会自动处理该映射的需要修改请求连接添加参数 tinyInt1isBit=false如下

jdbc:mysql://127.0.0.1:3306/mp?tinyInt1isBit=false

否则会报很多类型转换 boolean的错误
????记得生成成功之后,在测试运行的时候要在主启动类上添加@MapperScan(value = “”)哦。

结果图

技术图片

对于代码生成器的模板1(详细注释)

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;
import com.sun.javafx.scene.shape.PathUtils;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;

import java.io.File;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class CodeGenerator {

    public static void main(String[] args) {

        /*
            全局配置
        */
        String projectPath = System.getProperty("user.dir");
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(projectPath + "/src/main/java") // 生成路径
                .setAuthor("zjb")                     // 设置作者
                .setOpen(false)                         // 文件生成完成后是否用打开相应的生成路径
                .setFileOverride(true)                  // 是否覆盖已有文件
                .setIdType(IdType.ID_WORKER)                 // 主键策略
                .setEnableCache(true)                   // 是否开启二级缓存,默认false
                .setKotlin(false)                       // 开启 Kotlin 模式,默认false
                .setSwagger2(false)                     // 开启 swagger2 模式,默认false
//                .setActiveRecord(false)                 // 开启 ActiveRecord 模式
//                .setActiveRecord(true)                // AR模式,就是bean有增删改查方法,继承自Model类
                .setDateType(DateType.ONLY_DATE)        // 时间类型对应策略
//                .setDateType()
                .setEntityName("%sBean")              // 实体命名方式
                .setMapperName("%sMapper")              // mapper 命名方式
                .setXmlName("%sMapper")              // Mapper xml 命名方式
                .setServiceName("%sService")           // 设置生成的service接口的名字的首字母是否为I
                .setServiceImplName("%sServiceImp")                   //service impl 命名方式
                .setControllerName("%sController")
                .setBaseResultMap(true)                 // 是否要有映射ResultMap
                .setBaseColumnList(true);               // 是否要有基础的列

        /*

        数据源配置

        */
        MySqlQuery mySqlQuery = new MySqlQuery() {
            @Override
            public String[] fieldCustom() {
                return new String[]{"Default"};
            }
        };

//        String[] strings = mySqlQuery.fieldCustom();

        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8&useUnicode=true&useSSL=false&characterEncoding=utf8")
                .setDbType(DbType.MYSQL)     //设置数据库类型[必须属性]
                .setDriverName("com.mysql.cj.jdbc.Driver")
                .setDbQuery(mySqlQuery)  //
                .setUsername("root")
//                .setTypeConvert((globalConfig, fieldType) -> null) // 自定义映射属性
                .setPassword("");

        /*

        策略配置 数据表配置

        */
        StrategyConfig strategy = new StrategyConfig();
        strategy.setCapitalMode(true)           //全局大写命名
                .setSkipView(true)              // 是否跳过视图
                .setLogicDeleteFieldName("deleted") // 添加逻辑删除列
//                .setVersionFieldName("version1")    // 添加版本号充当乐观锁
                .setEntitySerialVersionUID(false)   //  实体是否生成 serialVersionUID,默认为true
                .setControllerMappingHyphenStyle(true) //驼峰转连字符,比如:/userEntity -> /user-entity
                .setEntityBuilderModel(true)               // 点进去有介绍
                .setEntityColumnConstant(true)          // 点进去有介绍
//                NamingStrategy.no_change
                .setNaming(NamingStrategy.underline_to_camel)   // 数据库表映射到实例命名,下划线到驼峰
                .setNameConvert(new INameConvert() {

                    @Override
                    public String entityNameConvert(TableInfo tableInfo) {
                        System.out.println(tableInfo.getName());
                        return tableInfo.getName();
                    }

                    @Override
                    public String propertyNameConvert(TableField field) {
                        System.out.println(field.getName());
                        return field.getName();
                    }
                }) // 名称转换接口
                .setColumnNaming(NamingStrategy.underline_to_camel)  // 数据库表中的字段映射到实例命名,下划线到驼峰
//                .setTablePrefix("kk")                 // 设置要生成代码的数据表前缀
//                .setFieldPrefix("kk")                 // 设置要生成代码的数据表中字段前缀
                .setInclude("wt_.+")                     // 设置要包含的表
//                .setTableFillList(Arrays.asList(new TableFill("id", FieldFill.INSERT))) //属性填充
//                .setColumnNaming()
//                .setExclude()                         // 与包含二选一,排除那些表,两个都允许正则表达式
//                .setSuperEntityClass() //设置实体类要继承的超类
//                .setSuperEntityColumns()      // 自定义基础的Entity类,公共字段
//                .setSuperMapperClass()        //  自定义继承的Mapper类全称,带包名
                .setEntityLombokModel(true) // 设置生成的实体类是Lombok模式
                .setRestControllerStyle(true);  //

        /*

        包配置

        */
        PackageConfig pc = new PackageConfig();

//        pathInfo = new HashMap<>(6);
//        setPathInfo(pathInfo, template.getEntity(getGlobalConfig().isKotlin()), outputDir, ConstVal.ENTITY_PATH, ConstVal.ENTITY);
//        setPathInfo(pathInfo, template.getMapper(), outputDir, ConstVal.MAPPER_PATH, ConstVal.MAPPER);
//        setPathInfo(pathInfo, template.getXml(), outputDir, ConstVal.XML_PATH, ConstVal.XML);
//        setPathInfo(pathInfo, template.getService(), outputDir, ConstVal.SERVICE_PATH, ConstVal.SERVICE);
//        setPathInfo(pathInfo, template.getServiceImpl(), outputDir, ConstVal.SERVICE_IMPL_PATH, ConstVal.SERVICE_IMPL);
//        setPathInfo(pathInfo, template.getController(), outputDir, ConstVal.CONTROLLER_PATH, ConstVal.CONTROLLER);

        pc.setParent("top.itreatment")    // 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
                .setMapper("mapper")      // 设置mapper输出的位置
                .setXml("mapper.xml")     // 设置mapper对应的xml输出的位置
//                .setModuleName("bc")      // 父设置模块名
//                .setPathInfo()           // 路径配置信息,就是配置各个文件模板的路径信息
                .setService("service")    // 设置service输出的位置
                .setController("controller") // 设置controller输出的位置
                .setServiceImpl("service.impl") // 设置serviceImpl输出的位置
                .setModuleName("bc")
                .setEntity("beans");        // 设置beans输出的位置

      /*
          自定义配置,少了这一步会出现空指针异常,在下面这个方法的返回时,出现空指针
           com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine.getObjectMap
      */
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<>();
                map.put("name", "zjb");
                map.put("age", 24);
                map.put("sex", "男");
                setMap(map);
            }
        };

//        cfg.setFileOutConfigList(Collections.singletonList(new FileOutConfig("entity.java.btl") {
//
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                return System.getProperty("user.home") + File.separator + "desktop" + File.separator + "123.txt";
//            }
//        }));
//        cfg.setFileCreate()       自定义判断是否创建文件

         /*

            代码生成器,将前面的初始化工作进行处理

         */
        AutoGenerator mpg = new AutoGenerator();
//        全局配置
        mpg.setGlobalConfig(gc);
//        数据源配置
        mpg.setDataSource(dsc);
//        策略配置
        mpg.setStrategy(strategy);
//        包配置
        mpg.setPackageInfo(pc);
//        自定义配置
        mpg.setCfg(cfg);
//        设置使用Beetl模板引擎
        BeetlTemplateEngine beetlTemplateEngine = new BeetlTemplateEngine();
        mpg.setTemplateEngine(beetlTemplateEngine);
//        执行
        mpg.execute();
    }
}
    */
    AutoGenerator mpg = new AutoGenerator();
// 全局配置
mpg.setGlobalConfig(gc);
// 数据源配置
mpg.setDataSource(dsc);
// 策略配置
mpg.setStrategy(strategy);
// 包配置
mpg.setPackageInfo(pc);
// 自定义配置
mpg.setCfg(cfg);
// 设置使用Beetl模板引擎
BeetlTemplateEngine beetlTemplateEngine = new BeetlTemplateEngine();
mpg.setTemplateEngine(beetlTemplateEngine);
// 执行
mpg.execute();
}
}

结尾

本文到这里就结束了,感谢看到最后的朋友,都看到最后了,点个赞再走啊,如有不对之处还请多多指正。
关注我带你解锁更多精彩内容

结尾

本文到这里就结束了,感谢看到最后的朋友,都看到最后了,点个赞再走啊,如有不对之处还请多多指正。
关注我带你解锁更多精彩内容

面试资料领取只需:?点击这里领取!!!!暗号:51CTO

Mybatis-Plus中的代码生成器AutoGenerator超详细解析!完整配置!

标签:misc   空指针   date   value   cep   增删改   介绍   rest   target   

原文地址:https://blog.51cto.com/14969174/2545500

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!