Search in sources :

Example 11 with TableInfo

use of com.baomidou.mybatisplus.generator.config.po.TableInfo in project drug by xiabud.

the class CodeGenerator method cg.

@Test
public void cg() {
    // 代码生成器
    AutoGenerator mpg = new AutoGenerator();
    // 全局配置
    GlobalConfig gc = new GlobalConfig();
    String projectPath = System.getProperty("user.dir");
    gc.setOutputDir(projectPath + "/src/main/java");
    gc.setAuthor("xiewc");
    gc.setOpen(false);
    gc.setFileOverride(false);
    gc.setServiceName("%sService");
    // gc.setSwagger2(true); 实体属性 Swagger2 注解
    mpg.setGlobalConfig(gc);
    // 数据源配置
    DataSourceConfig dsc = new DataSourceConfig();
    // dsc.setUrl("jdbc:oracle:thin:@10.20.11.11:1521:JSGLAX1");
    dsc.setUrl("jdbc:mysql://localhost:3306/drug");
    dsc.setDriverName("com.mysql.cj.jdbc.Driver");
    dsc.setUsername("root");
    dsc.setPassword("admin");
    dsc.setDbType(DbType.MYSQL);
    mpg.setDataSource(dsc);
    // 包配置
    PackageConfig pc = new PackageConfig();
    // pc.setModuleName(scanner("模块名"));
    pc.setParent("com.xiecode.drug");
    pc.setEntity("pojo");
    pc.setMapper("mapper");
    pc.setService("service");
    pc.setController("controller");
    // 自定义配置
    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/resources/mybatis/mapper/" + pc.getModuleName() + "/" + 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);
    mpg.setPackageInfo(pc);
    // 如果模板引擎是 velocity
    // 配置模板
    TemplateConfig templateConfig = new TemplateConfig();
    // 配置自定义输出模板
    // 指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
    // templateConfig.setEntity("templates/entity2.java");
    // templateConfig.setService();
    // templateConfig.setController();
    templateConfig.setXml(null);
    mpg.setTemplate(templateConfig);
    mpg.setPackageInfo(pc);
    // 如果模板引擎是 velocity
    // 策略配置
    StrategyConfig strategy = new StrategyConfig();
    strategy.setNaming(NamingStrategy.underline_to_camel);
    strategy.setColumnNaming(NamingStrategy.underline_to_camel);
    // strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
    strategy.setEntityLombokModel(true);
    strategy.setRestControllerStyle(true);
    // 公共父类
    // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
    // 写于父类中的公共字段
    // strategy.setSuperEntityColumns("id");
    // strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
    strategy.setInclude("sell_is_gone");
    strategy.setControllerMappingHyphenStyle(true);
    // strategy.setTablePrefix(pc.getModuleName() + "_");
    mpg.setStrategy(strategy);
    mpg.setTemplateEngine(new VelocityTemplateEngine());
    mpg.execute();
}
Also used : VelocityTemplateEngine(com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine) ArrayList(java.util.ArrayList) InjectionConfig(com.baomidou.mybatisplus.generator.InjectionConfig) TableInfo(com.baomidou.mybatisplus.generator.config.po.TableInfo) AutoGenerator(com.baomidou.mybatisplus.generator.AutoGenerator) Test(org.junit.jupiter.api.Test)

Example 12 with TableInfo

use of com.baomidou.mybatisplus.generator.config.po.TableInfo in project blade-tool by chillzhuang.

the class BladeCodeGenerator method run.

/**
 * 代码生成执行
 */
public void run() {
    Properties props = getProperties();
    String url = Func.toStr(this.url, props.getProperty("spring.datasource.url"));
    String username = Func.toStr(this.username, props.getProperty("spring.datasource.username"));
    String password = Func.toStr(this.password, props.getProperty("spring.datasource.password"));
    String servicePackage = serviceName.split("-").length > 1 ? serviceName.split("-")[1] : serviceName;
    Map<String, Object> customMap = new HashMap<>(11);
    customMap.put("codeName", codeName);
    customMap.put("serviceName", serviceName);
    customMap.put("servicePackage", servicePackage);
    customMap.put("servicePackageLowerCase", servicePackage.toLowerCase());
    customMap.put("tenantColumn", tenantColumn);
    customMap.put("hasWrapper", hasWrapper);
    Map<String, String> customFile = new HashMap<>(15);
    customFile.put("menu.sql", "/templates/sql/menu.sql.vm");
    customFile.put("entityVO.java", "/templates/entityVO.java.vm");
    customFile.put("entityDTO.java", "/templates/entityDTO.java.vm");
    if (hasWrapper) {
        customFile.put("wrapper.java", "/templates/wrapper.java.vm");
    }
    if (Func.isNotBlank(packageWebDir)) {
        if (Func.equals(systemName, DevelopConstant.SWORD_NAME)) {
            customFile.put("action.js", "/templates/sword/action.js.vm");
            customFile.put("model.js", "/templates/sword/model.js.vm");
            customFile.put("service.js", "/templates/sword/service.js.vm");
            customFile.put("list.js", "/templates/sword/list.js.vm");
            customFile.put("add.js", "/templates/sword/add.js.vm");
            customFile.put("edit.js", "/templates/sword/edit.js.vm");
            customFile.put("view.js", "/templates/sword/view.js.vm");
        } else if (Func.equals(systemName, DevelopConstant.SABER_NAME)) {
            customFile.put("api.js", "/templates/saber/api.js.vm");
            customFile.put("crud.vue", "/templates/saber/crud.vue.vm");
        }
    }
    FastAutoGenerator.create(url, username, password).globalConfig(builder -> builder.author(props.getProperty("author")).dateType(DateType.TIME_PACK).enableSwagger().outputDir(getOutputDir()).disableOpenDir()).packageConfig(builder -> builder.parent(packageName).controller("controller").entity("entity").service("service").serviceImpl("service.impl").mapper("mapper").xml("mapper")).strategyConfig(builder -> builder.addTablePrefix(tablePrefix).addInclude(includeTables).addExclude(excludeTables).entityBuilder().naming(NamingStrategy.underline_to_camel).columnNaming(NamingStrategy.underline_to_camel).enableLombok().superClass("org.springblade.core.mp.base.BaseEntity").addSuperEntityColumns(superEntityColumns).serviceBuilder().superServiceClass("org.springblade.core.mp.base.BaseService").superServiceImplClass("org.springblade.core.mp.base.BaseServiceImpl").formatServiceFileName("I%sService").formatServiceImplFileName("%sServiceImpl").mapperBuilder().enableMapperAnnotation().enableBaseResultMap().enableBaseColumnList().formatMapperFileName("%sMapper").formatXmlFileName("%sMapper").controllerBuilder().superClass("org.springblade.core.boot.ctrl.BladeController").formatFileName("%sController").enableRestStyle().enableHyphenStyle()).templateConfig(builder -> builder.disable(TemplateType.ENTITY).entity("/templates/entity.java.vm").service("/templates/service.java.vm").serviceImpl("/templates/serviceImpl.java.vm").mapper("/templates/mapper.java.vm").xml("/templates/mapper.xml.vm").controller("/templates/controller.java.vm")).injectionConfig(builder -> builder.beforeOutputFile((tableInfo, objectMap) -> System.out.println("tableInfo: " + tableInfo.getEntityName() + " objectMap: " + objectMap.size())).customMap(customMap).customFile(customFile)).templateEngine(new VelocityTemplateEngine() {

        @Override
        protected void outputCustomFile(Map<String, String> customFile, TableInfo tableInfo, Map<String, Object> objectMap) {
            String entityName = tableInfo.getEntityName();
            String entityNameLower = tableInfo.getEntityName().toLowerCase();
            customFile.forEach((key, value) -> {
                String outputPath = getPathInfo(OutputFile.other);
                if (StringUtil.equals(key, "menu.sql")) {
                    objectMap.put("entityKey", entityNameLower);
                    objectMap.put("menuId", IdWorker.getId());
                    objectMap.put("addMenuId", IdWorker.getId());
                    objectMap.put("editMenuId", IdWorker.getId());
                    objectMap.put("removeMenuId", IdWorker.getId());
                    objectMap.put("viewMenuId", IdWorker.getId());
                    outputPath = getOutputDir() + StringPool.SLASH + "sql" + StringPool.SLASH + entityNameLower + ".menu.sql";
                }
                if (StringUtil.equals(key, "entityVO.java")) {
                    outputPath = getOutputDir() + StringPool.SLASH + packageName.replace(StringPool.DOT, StringPool.SLASH) + StringPool.SLASH + "vo" + StringPool.SLASH + entityName + "VO" + StringPool.DOT_JAVA;
                }
                if (StringUtil.equals(key, "entityDTO.java")) {
                    outputPath = getOutputDir() + StringPool.SLASH + packageName.replace(StringPool.DOT, StringPool.SLASH) + StringPool.SLASH + "dto" + StringPool.SLASH + entityName + "DTO" + StringPool.DOT_JAVA;
                }
                if (StringUtil.equals(key, "wrapper.java")) {
                    outputPath = getOutputDir() + StringPool.SLASH + packageName.replace(StringPool.DOT, StringPool.SLASH) + StringPool.SLASH + "wrapper" + StringPool.SLASH + entityName + "Wrapper" + StringPool.DOT_JAVA;
                }
                if (StringUtil.equals(key, "action.js")) {
                    outputPath = getOutputWebDir() + StringPool.SLASH + "actions" + StringPool.SLASH + entityNameLower + ".js";
                }
                if (StringUtil.equals(key, "model.js")) {
                    outputPath = getOutputWebDir() + StringPool.SLASH + "models" + StringPool.SLASH + entityNameLower + ".js";
                }
                if (StringUtil.equals(key, "service.js")) {
                    outputPath = getOutputWebDir() + StringPool.SLASH + "services" + StringPool.SLASH + entityNameLower + ".js";
                }
                if (StringUtil.equals(key, "list.js")) {
                    outputPath = getOutputWebDir() + StringPool.SLASH + "pages" + StringPool.SLASH + StringUtil.upperFirst(servicePackage) + StringPool.SLASH + entityName + StringPool.SLASH + entityName + ".js";
                }
                if (StringUtil.equals(key, "add.js")) {
                    outputPath = getOutputWebDir() + StringPool.SLASH + "pages" + StringPool.SLASH + StringUtil.upperFirst(servicePackage) + StringPool.SLASH + entityName + StringPool.SLASH + entityName + "Add.js";
                }
                if (StringUtil.equals(key, "edit.js")) {
                    outputPath = getOutputWebDir() + StringPool.SLASH + "pages" + StringPool.SLASH + StringUtil.upperFirst(servicePackage) + StringPool.SLASH + entityName + StringPool.SLASH + entityName + "Edit.js";
                }
                if (StringUtil.equals(key, "view.js")) {
                    outputPath = getOutputWebDir() + StringPool.SLASH + "pages" + StringPool.SLASH + StringUtil.upperFirst(servicePackage) + StringPool.SLASH + entityName + StringPool.SLASH + entityName + "View.js";
                }
                if (StringUtil.equals(key, "api.js")) {
                    outputPath = getOutputWebDir() + StringPool.SLASH + "api" + StringPool.SLASH + servicePackage.toLowerCase() + StringPool.SLASH + entityNameLower + ".js";
                }
                if (StringUtil.equals(key, "crud.vue")) {
                    outputPath = getOutputWebDir() + StringPool.SLASH + "views" + StringPool.SLASH + servicePackage.toLowerCase() + StringPool.SLASH + entityNameLower + ".vue";
                }
                outputFile(new File(String.valueOf(outputPath)), objectMap, value, Boolean.TRUE);
            });
        }
    }).execute();
}
Also used : IdWorker(com.baomidou.mybatisplus.core.toolkit.IdWorker) Properties(java.util.Properties) StringUtil(org.springblade.core.tool.utils.StringUtil) ClassPathResource(org.springframework.core.io.ClassPathResource) IOException(java.io.IOException) HashMap(java.util.HashMap) File(java.io.File) OutputFile(com.baomidou.mybatisplus.generator.config.OutputFile) PropertiesLoaderUtils(org.springframework.core.io.support.PropertiesLoaderUtils) Slf4j(lombok.extern.slf4j.Slf4j) FastAutoGenerator(com.baomidou.mybatisplus.generator.FastAutoGenerator) TemplateType(com.baomidou.mybatisplus.generator.config.TemplateType) NamingStrategy(com.baomidou.mybatisplus.generator.config.rules.NamingStrategy) DevelopConstant(org.springblade.develop.constant.DevelopConstant) StringPool(com.baomidou.mybatisplus.core.toolkit.StringPool) TableInfo(com.baomidou.mybatisplus.generator.config.po.TableInfo) VelocityTemplateEngine(com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine) Map(java.util.Map) DateType(com.baomidou.mybatisplus.generator.config.rules.DateType) Data(lombok.Data) Func(org.springblade.core.tool.utils.Func) Resource(org.springframework.core.io.Resource) HashMap(java.util.HashMap) VelocityTemplateEngine(com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine) TableInfo(com.baomidou.mybatisplus.generator.config.po.TableInfo) Properties(java.util.Properties) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) OutputFile(com.baomidou.mybatisplus.generator.config.OutputFile)

Example 13 with TableInfo

use of com.baomidou.mybatisplus.generator.config.po.TableInfo 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 14 with TableInfo

use of com.baomidou.mybatisplus.generator.config.po.TableInfo 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)

Example 15 with TableInfo

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

the class ZipVelocityTemplateEngine method appendTableInfo.

/**
 * 添加
 * @param tableInfo 表信息
 * @param objectMap 模板对象
 */
private void appendTableInfo(TableInfo tableInfo, Map<String, Object> objectMap) {
    // 请求路径前缀
    objectMap.put("controllerMappingPrefix", tableInfo.getName().replaceFirst("_", "/"));
    // shiroPermissionsPrefix
    objectMap.put("shiroPermissionsPrefix", tableInfo.getName().replaceFirst("_", ":"));
    // 是否存在date 数据类型
    boolean hasDate = tableInfo.getFields().stream().anyMatch(f -> DbColumnType.DATE.getType().equals(f.getPropertyType()));
    if (hasDate) {
        tableInfo.getImportPackages().add("org.springframework.format.annotation.DateTimeFormat");
        tableInfo.getImportPackages().add("cn.hutool.core.date.DatePattern");
    }
    // 版本
    objectMap.put("version", EnableMybatisGenerator.VERSION);
    // 主键名称类型
    TableField pk = tableInfo.getFields().stream().filter(f -> f.isKeyFlag()).findFirst().orElse(null);
    objectMap.put("pk", pk);
    // 弹窗大小
    long i = tableInfo.getFields().stream().filter(f -> !(f.isKeyFlag() || f.getName().equals(getConfigBuilder().getStrategyConfig().getVersionFieldName()))).count();
    // 比率
    long rate = 30 + (i - 1) * 8;
    objectMap.put("openHeight", rate > 100 ? 100 : rate);
    // 模糊查询 tableInfo
    String comment = tableInfo.getComment();
    Map<String, String> map = this.commentToMap(comment);
    TableCommentParse parse = BeanUtil.mapToBean(map, TableCommentParse.class, true);
    objectMap.put("likeFields", parse.parseLike(tableInfo.getFields()));
    // 标题
    objectMap.put("menuTitle", parse.getTitle());
    // 关键字-保留字处理
    Map<String, String> kws = tableInfo.getFields().stream().collect(Collectors.toMap(TableField::getName, t -> KeyWordConstant.contains(t.getName()) ? "`" : ""));
    objectMap.put("kws", kws);
    if (kws.values().contains("`")) {
        tableInfo.getImportPackages().add("com.baomidou.mybatisplus.annotation.TableField");
    }
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) HtmlTemplateConfig(com.chao.cloud.common.extra.mybatis.generator.template.HtmlTemplateConfig) MapUtil(cn.hutool.core.map.MapUtil) TableCommentParse(com.chao.cloud.common.extra.mybatis.generator.parse.TableCommentParse) BeanUtil(cn.hutool.core.bean.BeanUtil) Template(org.apache.velocity.Template) InjectionConfig(com.baomidou.mybatisplus.generator.InjectionConfig) ConstVal(com.baomidou.mybatisplus.generator.config.ConstVal) VelocityEngine(org.apache.velocity.app.VelocityEngine) Map(java.util.Map) TableInfo(com.baomidou.mybatisplus.generator.config.po.TableInfo) BusinessException(com.chao.cloud.common.exception.BusinessException) CollectionUtils(com.baomidou.mybatisplus.core.toolkit.CollectionUtils) FileType(com.baomidou.mybatisplus.generator.config.rules.FileType) ZipEntry(java.util.zip.ZipEntry) KeyWordConstant(com.chao.cloud.common.extra.mybatis.constant.KeyWordConstant) FileOutConfig(com.baomidou.mybatisplus.generator.config.FileOutConfig) DbColumnType(com.baomidou.mybatisplus.generator.config.rules.DbColumnType) StringWriter(java.io.StringWriter) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) VelocityContext(org.apache.velocity.VelocityContext) File(java.io.File) IOUtils(org.apache.commons.io.IOUtils) TemplateConfig(com.baomidou.mybatisplus.generator.config.TemplateConfig) List(java.util.List) StrUtil(cn.hutool.core.util.StrUtil) Stream(java.util.stream.Stream) EnableMybatisGenerator(com.chao.cloud.common.extra.mybatis.annotation.EnableMybatisGenerator) VelocityTemplateEngine(com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine) ReflectUtil(cn.hutool.core.util.ReflectUtil) AbstractTemplateEngine(com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine) FileUtil(cn.hutool.core.io.FileUtil) TableField(com.baomidou.mybatisplus.generator.config.po.TableField) TableField(com.baomidou.mybatisplus.generator.config.po.TableField) TableCommentParse(com.chao.cloud.common.extra.mybatis.generator.parse.TableCommentParse)

Aggregations

TableInfo (com.baomidou.mybatisplus.generator.config.po.TableInfo)28 InjectionConfig (com.baomidou.mybatisplus.generator.InjectionConfig)23 ArrayList (java.util.ArrayList)20 AutoGenerator (com.baomidou.mybatisplus.generator.AutoGenerator)16 FreemarkerTemplateEngine (com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine)10 FileOutConfig (com.baomidou.mybatisplus.generator.config.FileOutConfig)6 TemplateConfig (com.baomidou.mybatisplus.generator.config.TemplateConfig)6 VelocityTemplateEngine (com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine)5 DataSourceConfig (com.baomidou.mybatisplus.generator.config.DataSourceConfig)4 IOException (java.io.IOException)4 Map (java.util.Map)4 GlobalConfig (com.baomidou.mybatisplus.generator.config.GlobalConfig)3 PackageConfig (com.baomidou.mybatisplus.generator.config.PackageConfig)3 StrategyConfig (com.baomidou.mybatisplus.generator.config.StrategyConfig)3 TableField (com.baomidou.mybatisplus.generator.config.po.TableField)3 File (java.io.File)3 FileUtil (cn.hutool.core.io.FileUtil)2 StrUtil (cn.hutool.core.util.StrUtil)2 FastAutoGenerator (com.baomidou.mybatisplus.generator.FastAutoGenerator)2 TableFill (com.baomidou.mybatisplus.generator.config.po.TableFill)2