MyBatis-Plus 核心功能-代碼生成器(舊)

2022-03-29 16:31 更新
注意:適用版本:mybatis-plus-generator 3.5.1 以下版本

AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過(guò) AutoGenerator 可以快速生成 ?Entity?、?Mapper?、?Mapper XML?、?Service?、?Controller ?等各個(gè)模塊的代碼,極大的提升了開(kāi)發(fā)效率。

演示效果圖:

generator

// 演示例子,執(zhí)行 main 方法控制臺(tái)輸入模塊表名回車(chē)自動(dòng)生成對(duì)應(yīng)項(xiàng)目目錄中
public class CodeGenerator {

    /**
     * <p>
     * 讀取控制臺(tái)內(nèi)容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("請(qǐng)輸入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("請(qǐng)輸入正確的" + 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("jobob");
        gc.setOpen(false);
        // gc.setSwagger2(true); 實(shí)體屬性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 數(shù)據(jù)源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("密碼");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(scanner("模塊名"));
        pc.setParent("com.baomidou.ant");
        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<>();
        // 自定義配置會(huì)被優(yōu)先輸出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化??!
                return projectPath + "/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) {
                // 判斷自定義文件夾是否需要?jiǎng)?chuàng)建
                checkDir("調(diào)用默認(rèn)方法創(chuàng)建的目錄,自定義目錄用");
                if (fileType == FileType.MAPPER) {
                    // 已經(jīng)生成 mapper 文件判斷存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允許生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定義輸出模板
        //指定自定義模板路徑,注意不要帶上.ftl/.vm, 會(huì)根據(jù)使用的模板引擎自動(dòng)識(shí)別
        // 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.setSuperEntityClass("你自己的父類(lèi)實(shí)體,沒(méi)有就不用設(shè)置!");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父類(lèi)
        strategy.setSuperControllerClass("你自己的父類(lèi)控制器,沒(méi)有就不用設(shè)置!");
        // 寫(xiě)于父類(lèi)中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(scanner("表名,多個(gè)英文逗號(hào)分割").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

使用教程

添加依賴(lài)

MyBatis-Plus 從 3.0.3 之后移除了代碼生成器與模板引擎的默認(rèn)依賴(lài),需要手動(dòng)添加相關(guān)依賴(lài):

  • 添加代碼生成器依賴(lài)
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.0</version>
</dependency>
  • 添加模板引擎依賴(lài),MyBatis-Plus 支持 ?Velocity?(默認(rèn))、?Freemarker?、?Beetl?,用戶(hù)可以選擇自己熟悉的模板引擎,如果都不滿(mǎn)足您的要求,可以采用自定義模板引擎。

Velocity(默認(rèn)):

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
</dependency>

Freemarker:

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

Beetl:

<dependency>
    <groupId>com.ibeetl</groupId>
    <artifactId>beetl</artifactId>
    <version>3.10.0.RELEASE</version>
</dependency>

注意!如果您選擇了非默認(rèn)引擎,需要在 ?AutoGenerator中 設(shè)置模板引擎。

AutoGenerator generator = new AutoGenerator();

// set freemarker engine
generator.setTemplateEngine(new FreemarkerTemplateEngine());

// set beetl engine
generator.setTemplateEngine(new BeetlTemplateEngine());

// set custom engine (reference class is your custom engine class)
generator.setTemplateEngine(new CustomTemplateEngine());

// other config
...

編寫(xiě)配置

MyBatis-Plus 的代碼生成器提供了大量的自定義參數(shù)供用戶(hù)選擇,能夠滿(mǎn)足絕大部分人的使用需求。

  • 配置 GlobalConfig
GlobalConfig globalConfig = new GlobalConfig();
globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");
globalConfig.setAuthor("jobob");
globalConfig.setOpen(false);
  • 配置 DataSourceConfig
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/ant?useUnicode=true&useSSL=false&characterEncoding=utf8");
dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("password");

自定義模板引擎

請(qǐng)繼承類(lèi) ?com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine?

自定義代碼模板

//指定自定義模板路徑, 位置:/resources/templates/entity2.java.ftl(或者是.vm)
//注意不要帶上.ftl(或者是.vm), 會(huì)根據(jù)使用的模板引擎自動(dòng)識(shí)別
TemplateConfig templateConfig = new TemplateConfig()
    .setEntity("templates/entity2.java");

AutoGenerator mpg = new AutoGenerator();
//配置自定義模板
mpg.setTemplate(templateConfig);

自定義屬性注入

InjectionConfig injectionConfig = new InjectionConfig() {
    //自定義屬性注入:abc
    //在.ftl(或者是.vm)模板中,通過(guò)${cfg.abc}獲取屬性
    @Override
    public void initMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
        this.setMap(map);
    }
};
AutoGenerator mpg = new AutoGenerator();
//配置自定義屬性注入
mpg.setCfg(injectionConfig);
entity2.java.ftl
自定義屬性注入abc=${cfg.abc}

entity2.java.vm
自定義屬性注入abc=$!{cfg.abc}

字段其他信息查詢(xún)注入

custom-fields

new DataSourceConfig().setDbQuery(new MySqlQuery() {

    /**
     * 重寫(xiě)父類(lèi)預(yù)留查詢(xún)自定義字段<br>
     * 這里查詢(xún)的 SQL 對(duì)應(yīng)父類(lèi) tableFieldsSql 的查詢(xún)字段,默認(rèn)不能滿(mǎn)足你的需求請(qǐng)重寫(xiě)它<br>
     * 模板中調(diào)用:  table.fields 獲取所有字段信息,
     * 然后循環(huán)字段獲取 field.customMap 從 MAP 中獲取注入字段如下  NULL 或者 PRIVILEGES
     */
    @Override
    public String[] fieldCustom() {
        return new String[]{"NULL", "PRIVILEGES"};
    }
})


以上內(nèi)容是否對(duì)您有幫助:
在線(xiàn)筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)