Search in sources :

Example 1 with TemplateConfig

use of com.baomidou.mybatisplus.generator.config.TemplateConfig in project code-generator-maven-plugin by mengweijin.

the class DefaultAutoGenerator method execute.

public void execute() {
    Parameters parameters = projectInfo.getParameters();
    String outputDir = FileUtil.file(projectInfo.getBaseDir(), "target/code-generator/").getAbsolutePath();
    // clean directory target/code-generator
    FileUtil.del(outputDir);
    FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(dataSourceConfigBuilder()).globalConfig(builder -> builder.fileOverride().author(parameters.getAuthor()).enableSwagger().disableOpenDir().outputDir(outputDir).dateType(DateType.TIME_PACK).commentDate("yyyy-MM-dd")).packageConfig(builder -> builder.parent(parameters.getOutputPackage())).templateConfig((Consumer<TemplateConfig.Builder>) TemplateConfig.Builder::disable).strategyConfig(builder -> builder.addInclude(this.trimItemName(parameters.getTables())).addTablePrefix(this.trimItemName(parameters.getTablePrefix())).entityBuilder().superClass(parameters.getSuperEntityClass()).enableChainModel().enableLombok().enableTableFieldAnnotation().versionColumnName("version").versionPropertyName("version").logicDeleteColumnName("deleted").logicDeletePropertyName("deleted").naming(NamingStrategy.underline_to_camel).addSuperEntityColumns(this.generateDefaultSuperEntityColumns()).controllerBuilder().superClass(parameters.getSuperControllerClass()).enableHyphenStyle().enableRestStyle().serviceBuilder().superServiceClass(parameters.getSuperServiceClass()).superServiceImplClass(parameters.getSuperServiceImplClass()).mapperBuilder().superClass(parameters.getSuperDaoClass()).enableBaseColumnList().enableBaseResultMap()).injectionConfig(builder -> {
        builder.beforeOutputFile(((tableInfo, objectMap) -> {
            enhanceObjectMap(objectMap, parameters);
            FileOutput.outputFile(tableInfo, objectMap, projectInfo, outputDir);
        }));
    }).templateEngine(TemplateEngineFactory.getTemplateEngine(this.projectInfo.getParameters().getTemplateType()));
    fastAutoGenerator.execute();
}
Also used : DbInfo(com.github.mengweijin.generator.entity.DbInfo) Arrays(java.util.Arrays) Getter(lombok.Getter) CustomerDataSource(com.github.mengweijin.generator.config.CustomerDataSource) ClassUtil(cn.hutool.core.util.ClassUtil) DataSourceConfig(com.baomidou.mybatisplus.generator.config.DataSourceConfig) ArrayList(java.util.ArrayList) FastAutoGenerator(com.baomidou.mybatisplus.generator.FastAutoGenerator) NamingStrategy(com.baomidou.mybatisplus.generator.config.rules.NamingStrategy) TableInfo(com.baomidou.mybatisplus.generator.config.po.TableInfo) Map(java.util.Map) DbInfoUtils(com.github.mengweijin.generator.util.DbInfoUtils) IdField(com.github.mengweijin.generator.entity.IdField) TemplateEngineFactory(com.github.mengweijin.generator.factory.TemplateEngineFactory) Parameters(com.github.mengweijin.generator.entity.Parameters) ProjectInfo(com.github.mengweijin.generator.entity.ProjectInfo) Field(java.lang.reflect.Field) Consumer(java.util.function.Consumer) TemplateConfig(com.baomidou.mybatisplus.generator.config.TemplateConfig) StrUtil(cn.hutool.core.util.StrUtil) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) DateType(com.baomidou.mybatisplus.generator.config.rules.DateType) FileOutput(com.github.mengweijin.generator.config.FileOutput) FileUtil(cn.hutool.core.io.FileUtil) TableField(com.baomidou.mybatisplus.generator.config.po.TableField) Parameters(com.github.mengweijin.generator.entity.Parameters) Consumer(java.util.function.Consumer) TemplateConfig(com.baomidou.mybatisplus.generator.config.TemplateConfig) FastAutoGenerator(com.baomidou.mybatisplus.generator.FastAutoGenerator)

Example 2 with TemplateConfig

use of com.baomidou.mybatisplus.generator.config.TemplateConfig in project spring-boot-web by wangchengming666.

the class MybatisPlusCodeGenerator method generateByTables.

private void generateByTables(String prefix, String packageName, String... tableNames) {
    // user -> UserService, 设置成true: user -> IUserService
    boolean serviceNameStartWithI = false;
    GlobalConfig config = new GlobalConfig();
    MybatisPlusConfig mybatis = new MybatisPlusConfig().setPrefix(prefix);
    // 数据库配置
    String dbUrl = mybatis.getString("jdbc-url");
    DataSourceConfig dataSourceConfig = new DataSourceConfig();
    dataSourceConfig.setDbType(DbType.MYSQL).setUrl(dbUrl).setUsername(mybatis.getString("username")).setPassword(mybatis.getString("password")).setDriverName(mybatis.getString("driver-class-name"));
    // 生成策略配置
    StrategyConfig strategyConfig = new StrategyConfig();
    // 全局大写命名 ORACLE 注意
    strategyConfig.setCapitalMode(true).setEntityLombokModel(false).setNaming(NamingStrategy.underline_to_camel).setInclude(// 修改替换成你需要的表名,多个表名传数组
    tableNames);
    /**
     * 设置超类
     */
    strategyConfig.setSuperEntityClass("com.myname.skeleton.commons.BaseObject");
    // 输出目录
    config.setActiveRecord(false).setOutputDir(System.getProperty("user.dir") + "//src//main//java").setFileOverride(true);
    if (!serviceNameStartWithI) {
        config.setServiceName("%sService");
    }
    TemplateConfig tc = new TemplateConfig();
    // 不输出web层
    tc.setController(null);
    /**
     * 如果是重新生成,只生成 model
     */
    if (false) {
        tc.setMapper(null);
        tc.setService(null);
        tc.setServiceImpl(null);
        tc.setXml(null);
    }
    new AutoGenerator().setGlobalConfig(config).setDataSource(dataSourceConfig).setStrategy(strategyConfig).setTemplate(tc).setPackageInfo(new PackageConfig().setParent(packageName).setXml("mapper." + mybatis.getSchemaName(dbUrl)).setMapper("mapper." + mybatis.getSchemaName(dbUrl)).setEntity("entity." + mybatis.getSchemaName(dbUrl))).execute();
}
Also used : StrategyConfig(com.baomidou.mybatisplus.generator.config.StrategyConfig) DataSourceConfig(com.baomidou.mybatisplus.generator.config.DataSourceConfig) GlobalConfig(com.baomidou.mybatisplus.generator.config.GlobalConfig) TemplateConfig(com.baomidou.mybatisplus.generator.config.TemplateConfig) PackageConfig(com.baomidou.mybatisplus.generator.config.PackageConfig) AutoGenerator(com.baomidou.mybatisplus.generator.AutoGenerator)

Example 3 with TemplateConfig

use of com.baomidou.mybatisplus.generator.config.TemplateConfig in project ddf-common by dongfangding.

the class CodeGenerator method generate.

public static void generate() {
    // 代码生成器
    AutoGenerator mpg = new AutoGenerator();
    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir") + "/ddf-common-mybatis-generator";
    gc.setOutputDir(projectPath + "/src/main/java");
    gc.setAuthor("mybatis-plus-generator");
    gc.setFileOverride(true);
    gc.setActiveRecord(false);
    gc.setBaseResultMap(true);
    gc.setBaseColumnList(true);
    gc.setEnableCache(false);
    gc.setOpen(false);
    // gc.setSwagger2(true); 实体属性 Swagger2 注解
    mpg.setGlobalConfig(gc);
    // 数据源配置
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://localhost:3306/better-together?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&autoReconnect=true&failOverReadOnly=false&maxReconnects=10&tinyInt1isBit=false");
    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("123");
    dsc.setTypeConvert(new MySqlTypeConvertCustom());
    mpg.setDataSource(dsc);
    // 包配置
    PackageConfig pc = new PackageConfig();
    // pc.setModuleName(scanner("模块名"));
    pc.setParent("com.ddf.better.together");
    pc.setEntity("model.entity");
    /*        pc.setService("com.ddf.boot.service");
        pc.setServiceImpl("com.ddf.boot.service.impl");
        pc.setController("com.ddf.boot.controller");
        pc.setMapper("com.ddf.boot.mapper");*/
    pc.setXml(null);
    mpg.setPackageInfo(pc);
    // 自定义配置
    InjectionConfig cfg = new InjectionConfig() {

        @Override
        public void initMap() {
        // to do nothing
        }
    };
    // 如果模板引擎是 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/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
        }
    });
    /*        // 自定义vo
        focList.add(new FileOutConfig("myTemplates/vo.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return gc.getOutputDir() + "/com/code/generator/domain/vo/"
                        + tableInfo.getEntityName()+"Vo" + StringPool.DOT_JAVA;
            }
        });*/
    // 应用自定义文件输出
    cfg.setFileOutConfigList(focList);
    mpg.setCfg(cfg);
    // 配置模板
    TemplateConfig templateConfig = new TemplateConfig();
    templateConfig.setXml(null);
    mpg.setTemplate(templateConfig);
    mpg.setTemplateEngine(new VelocityTemplateEngine());
    // 策略配置
    StrategyConfig strategy = new StrategyConfig();
    // 过滤表名前缀
    strategy.setTablePrefix("");
    // 驼峰命名
    strategy.setNaming(NamingStrategy.underline_to_camel);
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    // 设置父类,如果存在的话
    // strategy.setSuperEntityClass("com.ddf.boot.common.core.model.BaseDomain");
    strategy.setEntityLombokModel(true);
    strategy.setRestControllerStyle(true);
    // 写于父类中的公共字段
    // strategy.setSuperEntityColumns("id", "create_by", "create_time", "modify_by", "modify_time", "is_del", "version");
    // 其它带父类的
    // strategy.setSuperServiceClass("");
    strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
    strategy.setTablePrefix(pc.getModuleName() + "_");
    mpg.setStrategy(strategy);
    mpg.execute();
}
Also used : DataSourceConfig(com.baomidou.mybatisplus.generator.config.DataSourceConfig) GlobalConfig(com.baomidou.mybatisplus.generator.config.GlobalConfig) VelocityTemplateEngine(com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine) ArrayList(java.util.ArrayList) TemplateConfig(com.baomidou.mybatisplus.generator.config.TemplateConfig) InjectionConfig(com.baomidou.mybatisplus.generator.InjectionConfig) PackageConfig(com.baomidou.mybatisplus.generator.config.PackageConfig) FileOutConfig(com.baomidou.mybatisplus.generator.config.FileOutConfig) StrategyConfig(com.baomidou.mybatisplus.generator.config.StrategyConfig) TableInfo(com.baomidou.mybatisplus.generator.config.po.TableInfo) AutoGenerator(com.baomidou.mybatisplus.generator.AutoGenerator)

Example 4 with TemplateConfig

use of com.baomidou.mybatisplus.generator.config.TemplateConfig in project demo-parent by yindanqing925.

the class MysqlGenerator method main.

/**
 * RUN THIS
 */
public static void main(String[] args) {
    // 代码生成器
    AutoGenerator mpg = new AutoGenerator();
    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir") + "/mybatisplus-demo";
    gc.setOutputDir(projectPath + "/src/main/java");
    // TODO 设置用户名
    gc.setAuthor("yindanqing");
    gc.setOpen(false);
    // service 命名方式
    gc.setServiceName("%sService");
    // service impl 命名方式
    gc.setServiceImplName("%sServiceImpl");
    // 自定义文件命名,注意 %s 会自动填充表实体属性!
    gc.setMapperName("%sMapper");
    gc.setXmlName("%sMapper");
    gc.setFileOverride(true);
    gc.setActiveRecord(true);
    // XML 二级缓存
    gc.setEnableCache(false);
    // XML ResultMap
    gc.setBaseResultMap(true);
    // XML columList
    gc.setBaseColumnList(false);
    mpg.setGlobalConfig(gc);
    // TODO 数据源配置
    DataSourceConfig dsc = new DataSourceConfig();
    dsc.setUrl("jdbc:mysql://cdb-1v2wt3os.bj.tencentcdb.com:10243/nh?useUnicode=true&characterEncoding=UTF8");
    dsc.setDriverName("com.mysql.jdbc.Driver");
    dsc.setUsername("user_dev");
    dsc.setPassword("user_dev_nh");
    mpg.setDataSource(dsc);
    // TODO 包配置
    PackageConfig pc = new PackageConfig();
    // pc.setModuleName(scanner("模块名"));
    pc.setParent("org.nh.mybatisplus.dict");
    pc.setEntity("domain");
    pc.setService("service");
    pc.setServiceImpl("service.impl");
    mpg.setPackageInfo(pc);
    // 自定义需要填充的字段
    List<TableFill> tableFillList = new ArrayList<>();
    // 如 每张表都有一个创建时间、修改时间
    // 而且这基本上就是通用的了,新增时,创建时间和修改时间同时修改
    // 修改时,修改时间会修改,
    // 虽然像Mysql数据库有自动更新几只,但像ORACLE的数据库就没有了,
    // 使用公共字段填充功能,就可以实现,自动按场景更新了。
    // 如下是配置
    // TableFill createField = new TableFill("gmt_create", FieldFill.INSERT);
    // TableFill modifiedField = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
    // tableFillList.add(createField);
    // tableFillList.add(modifiedField);
    // 自定义配置
    InjectionConfig cfg = new InjectionConfig() {

        @Override
        public void initMap() {
        // to do nothing
        }
    };
    List<FileOutConfig> focList = new ArrayList<>();
    focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {

        @Override
        public String outputFile(TableInfo tableInfo) {
            // 自定义输入文件名称
            return projectPath + "/src/main/java/org/nh/mybatisplus/dict/mapper/" + tableInfo.getEntityName() + "Mapper" + ".xml";
        }
    });
    cfg.setFileOutConfigList(focList);
    mpg.setCfg(cfg);
    mpg.setTemplate(new TemplateConfig().setXml(null));
    // 策略配置
    StrategyConfig strategy = new StrategyConfig();
    strategy.setNaming(NamingStrategy.underline_to_camel);
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    strategy.setEntityLombokModel(true);
    // 设置逻辑删除键
    strategy.setLogicDeleteFieldName("deleted");
    // TODO 指定生成的bean的数据库表名
    strategy.setInclude("transfer_dict");
    // strategy.setSuperEntityColumns("id");
    // 驼峰转连字符
    strategy.setControllerMappingHyphenStyle(true);
    mpg.setStrategy(strategy);
    // 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
    mpg.setTemplateEngine(new FreemarkerTemplateEngine());
    mpg.execute();
}
Also used : DataSourceConfig(com.baomidou.mybatisplus.generator.config.DataSourceConfig) GlobalConfig(com.baomidou.mybatisplus.generator.config.GlobalConfig) ArrayList(java.util.ArrayList) TemplateConfig(com.baomidou.mybatisplus.generator.config.TemplateConfig) InjectionConfig(com.baomidou.mybatisplus.generator.InjectionConfig) PackageConfig(com.baomidou.mybatisplus.generator.config.PackageConfig) FileOutConfig(com.baomidou.mybatisplus.generator.config.FileOutConfig) TableFill(com.baomidou.mybatisplus.generator.config.po.TableFill) StrategyConfig(com.baomidou.mybatisplus.generator.config.StrategyConfig) TableInfo(com.baomidou.mybatisplus.generator.config.po.TableInfo) FreemarkerTemplateEngine(com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine) AutoGenerator(com.baomidou.mybatisplus.generator.AutoGenerator)

Example 5 with TemplateConfig

use of com.baomidou.mybatisplus.generator.config.TemplateConfig in project chao-cloud by chaojunzi.

the class ZipVelocityTemplateEngine method batchOutput.

/**
 * 输出到文件流
 * @param zip zip输出流
 * @return {@link AbstractTemplateEngine}
 * @throws Exception 生成文件模板时抛出的异常
 */
public AbstractTemplateEngine batchOutput(ZipOutputStream zip) throws Exception {
    try {
        List<TableInfo> tableInfoList = getConfigBuilder().getTableInfoList();
        for (TableInfo tableInfo : tableInfoList) {
            Map<String, Object> objectMap = super.getObjectMap(tableInfo);
            Map<String, String> pathInfo = getConfigBuilder().getPathInfo();
            TemplateConfig template = getConfigBuilder().getTemplate();
            // 自定义内容
            InjectionConfig injectionConfig = getConfigBuilder().getInjectionConfig();
            if (null != injectionConfig) {
                injectionConfig.initMap();
                objectMap.put("cfg", injectionConfig.getMap());
                List<FileOutConfig> focList = injectionConfig.getFileOutConfigList();
                if (CollectionUtils.isNotEmpty(focList)) {
                    for (FileOutConfig foc : focList) {
                        if (isCreate(FileType.OTHER, foc.outputFile(tableInfo))) {
                            writer(objectMap, foc.getTemplatePath(), foc.outputFile(tableInfo));
                        }
                    }
                }
            }
            // appendTableInfo
            this.appendTableInfo(tableInfo, objectMap);
            VelocityContext context = new VelocityContext(objectMap);
            // MpEntity.java
            String entityName = tableInfo.getEntityName();
            if (null != entityName && null != pathInfo.get(ConstVal.ENTITY_PATH)) {
                String entityFile = String.format((pathInfo.get(ConstVal.ENTITY_PATH) + File.separator + "%s" + suffixJavaOrKt()), entityName);
                if (isCreate(FileType.ENTITY, entityFile)) {
                    this.writer(context, templateFilePath(template.getEntity(getConfigBuilder().getGlobalConfig().isKotlin())), zip, entityFile);
                }
            }
            // MpMapper.java
            if (null != tableInfo.getMapperName() && null != pathInfo.get(ConstVal.MAPPER_PATH)) {
                String mapperFile = String.format((pathInfo.get(ConstVal.MAPPER_PATH) + File.separator + tableInfo.getMapperName() + suffixJavaOrKt()), entityName);
                if (isCreate(FileType.MAPPER, mapperFile)) {
                    this.writer(context, templateFilePath(template.getMapper()), zip, mapperFile);
                }
            }
            // MpMapper.xml
            if (null != tableInfo.getXmlName() && null != pathInfo.get(ConstVal.XML_PATH)) {
                String xmlFile = String.format((pathInfo.get(ConstVal.XML_PATH) + File.separator + tableInfo.getXmlName() + ConstVal.XML_SUFFIX), entityName);
                if (isCreate(FileType.XML, xmlFile)) {
                    this.writer(context, templateFilePath(template.getXml()), zip, xmlFile);
                }
            }
            // IMpService.java
            if (null != tableInfo.getServiceName() && null != pathInfo.get(ConstVal.SERVICE_PATH)) {
                String serviceFile = String.format((pathInfo.get(ConstVal.SERVICE_PATH) + File.separator + tableInfo.getServiceName() + suffixJavaOrKt()), entityName);
                if (isCreate(FileType.SERVICE, serviceFile)) {
                    this.writer(context, templateFilePath(template.getService()), zip, serviceFile);
                }
            }
            // MpServiceImpl.java
            if (null != tableInfo.getServiceImplName() && null != pathInfo.get(ConstVal.SERVICE_IMPL_PATH)) {
                String implFile = String.format((pathInfo.get(ConstVal.SERVICE_IMPL_PATH) + File.separator + tableInfo.getServiceImplName() + suffixJavaOrKt()), entityName);
                if (isCreate(FileType.SERVICE_IMPL, implFile)) {
                    this.writer(context, templateFilePath(template.getServiceImpl()), zip, implFile);
                }
            }
            // MpController.java
            if (null != tableInfo.getControllerName() && null != pathInfo.get(ConstVal.CONTROLLER_PATH)) {
                String controllerFile = String.format((pathInfo.get(ConstVal.CONTROLLER_PATH) + File.separator + tableInfo.getControllerName() + suffixJavaOrKt()), entityName);
                if (isCreate(FileType.CONTROLLER, controllerFile)) {
                    this.writer(context, templateFilePath(template.getController()), zip, controllerFile);
                }
            }
            // html->模板
            if (template instanceof HtmlTemplateConfig) {
                this.genHtml(tableInfo, (HtmlTemplateConfig) template, context, zip);
            }
        }
    } catch (Exception e) {
        logger.error("无法创建文件,请检查配置信息!", e);
        throw e;
    }
    return this;
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) HtmlTemplateConfig(com.chao.cloud.common.extra.mybatis.generator.template.HtmlTemplateConfig) HtmlTemplateConfig(com.chao.cloud.common.extra.mybatis.generator.template.HtmlTemplateConfig) TemplateConfig(com.baomidou.mybatisplus.generator.config.TemplateConfig) InjectionConfig(com.baomidou.mybatisplus.generator.InjectionConfig) BusinessException(com.chao.cloud.common.exception.BusinessException) IOException(java.io.IOException) FileOutConfig(com.baomidou.mybatisplus.generator.config.FileOutConfig) TableInfo(com.baomidou.mybatisplus.generator.config.po.TableInfo)

Aggregations

TemplateConfig (com.baomidou.mybatisplus.generator.config.TemplateConfig)8 DataSourceConfig (com.baomidou.mybatisplus.generator.config.DataSourceConfig)6 AutoGenerator (com.baomidou.mybatisplus.generator.AutoGenerator)5 GlobalConfig (com.baomidou.mybatisplus.generator.config.GlobalConfig)5 PackageConfig (com.baomidou.mybatisplus.generator.config.PackageConfig)5 StrategyConfig (com.baomidou.mybatisplus.generator.config.StrategyConfig)5 TableInfo (com.baomidou.mybatisplus.generator.config.po.TableInfo)5 InjectionConfig (com.baomidou.mybatisplus.generator.InjectionConfig)4 FileOutConfig (com.baomidou.mybatisplus.generator.config.FileOutConfig)4 ArrayList (java.util.ArrayList)4 FreemarkerTemplateEngine (com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine)2 FileUtil (cn.hutool.core.io.FileUtil)1 ClassUtil (cn.hutool.core.util.ClassUtil)1 StrUtil (cn.hutool.core.util.StrUtil)1 FastAutoGenerator (com.baomidou.mybatisplus.generator.FastAutoGenerator)1 TableField (com.baomidou.mybatisplus.generator.config.po.TableField)1 TableFill (com.baomidou.mybatisplus.generator.config.po.TableFill)1 DateType (com.baomidou.mybatisplus.generator.config.rules.DateType)1 NamingStrategy (com.baomidou.mybatisplus.generator.config.rules.NamingStrategy)1 VelocityTemplateEngine (com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine)1