MyBatisPlus 3.x 代碼生成器

相關(guān)資料以及注意事項(xiàng):

簡(jiǎn)介

AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過(guò) AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個(gè)模塊的代碼,極大的提升了開發(fā)效率。之前也講過(guò)MyBatis的生成器 Mybatis - Mybatis Generator插件,相比之前MyBatisPlus的生成器用起來(lái)更加的方便,更加的強(qiáng)大。

生成模版

添加MAVEN,設(shè)置DataSource,生成規(guī)則以及生成路徑。從本文工程中的MyBatisGenerator取用即可。

MAVEN

  <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.9</version>
        </dependency>

MysqlGenerator.java

/**
 * Copyright (c) 2011-2016, hubin (jobob@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.*;

/**
 * <p>
 * 代碼生成器演示
 * </p>
 *
 * @author hubin
 * @since 2016-12-01
 */
public class MysqlGenerator extends GeneratorTest {

    /**
     * <p>
     * MySQL 生成演示
     * </p>
     */
    public static void main(String[] args) {
        int result = scanner();
        // 自定義需要填充的字段
        List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE));

        // 代碼生成器
        AutoGenerator mpg = new AutoGenerator().setGlobalConfig(
            // 全局配置
            new GlobalConfig()
                .setOutputDir("D:\\SpringBootStudy\\MyBatisPlus\\MyBatisGenerator\\src\\main\\java")//輸出目錄
                .setFileOverride(true)// 是否覆蓋文件
                .setActiveRecord(true)// 開啟 activeRecord 模式
                .setEnableCache(false)// XML 二級(jí)緩存
                .setBaseResultMap(true)// XML ResultMap
                .setBaseColumnList(true)// XML columList
                //.setKotlin(true) 是否生成 kotlin 代碼
                .setAuthor("BaoZhou")
            // 自定義文件命名,注意 %s 會(huì)自動(dòng)填充表實(shí)體屬性!
            // .setEntityName("%sEntity");
            // .setMapperName("%sDao")
            // .setXmlName("%sDao")
            // .setServiceName("MP%sService")
            // .setServiceImplName("%sServiceDiy")
            // .setControllerName("%sAction")
        ).setDataSource(
            // 數(shù)據(jù)源配置
            new DataSourceConfig()
                .setDbType(DbType.MYSQL)// 數(shù)據(jù)庫(kù)類型
                //.setTypeConvert(new MySqlTypeConvert() {
                //    // 自定義數(shù)據(jù)庫(kù)表字段類型轉(zhuǎn)換【可選】
                //    @Override
                //    public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
                //        System.out.println("轉(zhuǎn)換類型:" + fieldType);
                //        // if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
                //        //    return DbColumnType.BOOLEAN;
                //        // }
                //        return super.processTypeConvert(globalConfig, fieldType);
                //    }
                //})
                .setDriverName("com.mysql.cj.jdbc.Driver")
                .setUsername("root")
                .setPassword("123456")
                .setUrl("jdbc:mysql://192.168.15.128:3306/myBatisPlus?characterEncoding=utf8")
        ).setStrategy(
            // 策略配置
            new StrategyConfig()
                // .setCapitalMode(true)// 全局大寫命名
                // .setDbColumnUnderline(true)//全局下劃線命名
                .setTablePrefix(new String[]{"tbl_", "mp_"})// 此處可以修改為您的表前綴
                .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
                // .setInclude(new String[] { "user" }) // 需要生成的表
                // .setExclude(new String[]{"test"}) // 排除生成的表
                // 自定義實(shí)體父類
                // .setSuperEntityClass("com.baomidou.demo.TestEntity")
                // 自定義實(shí)體,公共字段
                .setSuperEntityColumns(new String[]{"test_id"})
                .setTableFillList(tableFillList)
            // 自定義 mapper 父類
            // .setSuperMapperClass("com.baomidou.demo.TestMapper")
            // 自定義 service 父類
            // .setSuperServiceClass("com.baomidou.demo.TestService")
            // 自定義 service 實(shí)現(xiàn)類父類
            // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl")
            // 自定義 controller 父類
            // .setSuperControllerClass("com.baomidou.demo.TestController")
            // 【實(shí)體】是否生成字段常量(默認(rèn) false)
            // public static final String ID = "test_id";
            // .setEntityColumnConstant(true)
            // 【實(shí)體】是否為構(gòu)建者模型(默認(rèn) false)
            // public User setName(String name) {this.name = name; return this;}
            // .setEntityBuilderModel(true)
            // 【實(shí)體】是否為lombok模型(默認(rèn) false)<a >document</a>
            // .setEntityLombokModel(true)
            // Boolean類型字段是否移除is前綴處理
            // .setEntityBooleanColumnRemoveIsPrefix(true)
            // .setRestControllerStyle(true)
            // .setControllerMappingHyphenStyle(true)
        ).setPackageInfo(
            // 包配置
            new PackageConfig()
                .setModuleName("test")
                .setParent("com.bzcoder")// 自定義包路徑
                .setController("controller")// 這里是控制器包名,默認(rèn) web
        ).setCfg(
            // 注入自定義配置,可以在 VM 中使用 cfg.abc 設(shè)置的值
            new InjectionConfig() {
                @Override
                public void initMap() {
                    Map<String, Object> map = new HashMap<>();
                    map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                    this.setMap(map);
                }
            }.setFileOutConfigList(Collections.<FileOutConfig>singletonList(new FileOutConfig(
                "/templates/mapper.xml" + ((1 == result) ? ".ftl" : ".vm")) {
                // 自定義輸出文件目錄
                @Override
                public String outputFile(TableInfo tableInfo) {
                    return "D:/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
                }
            }))
        ).setTemplate(
            // 關(guān)閉默認(rèn) xml 生成,調(diào)整生成 至 根目錄
            new TemplateConfig().setXml(null)
            // 自定義模板配置,模板可以參考源碼 /mybatis-plus/src/main/resources/template 使用 copy
            // 至您項(xiàng)目 src/main/resources/template 目錄下,模板名稱也可自定義如下配置:
            // .setController("...");
            // .setEntity("...");
            // .setMapper("...");
            // .setXml("...");
            // .setService("...");
            // .setServiceImpl("...");
        );
        // 執(zhí)行生成
        if (1 == result) {
            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        }
        mpg.execute();

        // 打印注入設(shè)置,這里演示模板里面怎么獲取注入內(nèi)容【可無(wú)】
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }

}

GeneratorTest.java

package com.generator;

import java.util.Scanner;


/**
 * <p>
 * Generator test
 * </p>
 *
 * @author hubin
 * @since 2018-01-11
 */
public class GeneratorTest {

    /**
     * <p>
     * 讀取控制臺(tái)內(nèi)容
     * </p>
     */
    public static int scanner() {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append(" ??!代碼生成, 輸入 0 表示使用 Velocity 引擎 ??!");
        help.append("\n對(duì)照表:");
        help.append("\n0 = Velocity 引擎");
        help.append("\n1 = Freemarker 引擎");
        help.append("\n請(qǐng)輸入:");
        System.out.println(help.toString());
        int slt = 0;
        // 現(xiàn)在有輸入數(shù)據(jù)
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if ("1".equals(ipt)) {
                slt = 1;
            }
        }
        return slt;
    }
}

運(yùn)行結(jié)果

生成目錄

生成完畢
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1 Mybatis入門 1.1 單獨(dú)使用jdbc編程問(wèn)題總結(jié) 1.1.1 jdbc程序 上邊使...
    哇哈哈E閱讀 3,410評(píng)論 0 38
  • 1. 簡(jiǎn)介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存儲(chǔ)過(guò)程以及高級(jí)映射的優(yōu)秀的...
    笨鳥慢飛閱讀 6,217評(píng)論 0 4
  • 之前我在調(diào)試的時(shí)候,只會(huì)斷點(diǎn)調(diào)試,一步一步往下走,看了別人寫的一篇文章才知道,原來(lái)斷點(diǎn)調(diào)試還可以這么使用. 第一,...
    正陽(yáng)Android閱讀 1,084評(píng)論 3 8
  • 早上,我走到窗前??吹酵饷娲笱┘娂?,心里高興極了! 我像小兔子一樣興奮的沖出家門,我先是在雪地里跑...
    楚小妞閱讀 183評(píng)論 0 0
  • 易云下車拿起長(zhǎng)刀緩步走入喪尸群中,長(zhǎng)刀輪起離易云最近的三個(gè)喪尸被削掉了腦袋,易云跳起,一只腳踢在一個(gè)能姓喪尸的胸口...
    我為你風(fēng)中立閱讀 3,795評(píng)論 0 1

友情鏈接更多精彩內(nèi)容