1. 程式人生 > 實用技巧 >MyBatis-Plus程式碼自動生成器

MyBatis-Plus程式碼自動生成器

package watt.gasleakage;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
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.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @Author watt
 * @Description 程式碼生成器
 * @Date 2020/12/17 15:38
 */
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.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("請輸入正確的" + tip + "!");
    }

    public static void main(String[] args) {
        // 程式碼生成器
        AutoGenerator mpg = new AutoGenerator();

        // 1、全域性配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir"); // 當前專案目錄
        gc.setOutputDir(projectPath + "/src/main/java"); // 輸出路徑
        gc.setFileOverride(true); // 預設false,是否覆蓋已生成檔案
        gc.setAuthor("watt"); // 作者
        gc.setOpen(false); //預設true,是否開啟輸出目錄
        gc.setSwagger2(true); //實體屬性 Swagger2 註解
        // 自定義檔名,%s會自動填充表實體屬性
        gc.setServiceName("%sService"); // Service介面的名字,去除Service的I字首
        gc.setIdType(IdType.AUTO); // 主鍵型別
        gc.setDateType(DateType.ONLY_DATE); // 日期型別
        mpg.setGlobalConfig(gc);

        // 2、資料庫連線配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/gasleakage?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("123456");
        dsc.setDbType(DbType.MYSQL); // 資料庫型別
        mpg.setDataSource(dsc);

        // 3、包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null); // 所屬模組的名稱
        pc.setParent("watt.gasleakage"); // 程式碼生成到哪個包下面
        pc.setEntity("entity"); // 生成包的名稱
        pc.setMapper("mapper");
        pc.setService("service");
        pc.setController("controller");
        mpg.setPackageInfo(pc);

        // 4、策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel); // 表對映 駝峰命名
        strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 欄位對映
        strategy.setEntityLombokModel(true); // 預設false,是否使用lombok
        strategy.setRestControllerStyle(true); // Restful
        strategy.setInclude(scanner("表名,多個英文逗號分割").split(",")); // 設定要對映的表名
        strategy.setControllerMappingHyphenStyle(true); // url中支援下劃線,localhost:8080/hello_id_2
        strategy.setLogicDeleteFieldName("deleted"); // 邏輯刪除的名字
        // strategy.setTablePrefix("m_"); // 表的字首
        // 自動填充配置
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time",FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(createTime);
        tableFills.add(updateTime);
        strategy.setTableFillList(tableFills);
        strategy.setVersionFieldName("version"); // 樂觀鎖
        mpg.setStrategy(strategy);

        // 5、模板配置
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 6、模板引擎配置
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 7、自定義配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        String templatePath = "/templates/mapper.xml.ftl"; // 如果模板引擎是 freemarker
        // String templatePath = "/templates/mapper.xml.vm"; // 如果模板引擎是 velocity

        List<FileOutConfig> focList = new ArrayList<>(); // 自定義輸出配置
        focList.add(new FileOutConfig(templatePath) { // 自定義配置會被優先輸出
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定義輸出檔名 , 如果你 Entity 設定了前後綴、此處注意 xml 的名稱會跟著發生變化!!
                return projectPath + "/src/main/resources/mapper/"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 執行配置
        mpg.execute();
    }
}