瀏覽代碼

优化重构多种模板引擎支持

= 7 年之前
父節點
當前提交
13a13b3632

+ 150 - 1
mybatis-plus-generate/src/main/java/com/baomidou/mybatisplus/generator/engine/AbstractTemplateEngine.java

@@ -17,13 +17,27 @@ package com.baomidou.mybatisplus.generator.engine;
 
 import java.io.File;
 import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
+import org.apache.velocity.VelocityContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import com.baomidou.mybatisplus.generator.config.ConstVal;
+import com.baomidou.mybatisplus.generator.config.FileOutConfig;
+import com.baomidou.mybatisplus.generator.config.GlobalConfig;
+import com.baomidou.mybatisplus.generator.config.TemplateConfig;
 import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
+import com.baomidou.mybatisplus.generator.config.po.TableInfo;
+import com.baomidou.mybatisplus.toolkit.CollectionUtils;
+import com.baomidou.mybatisplus.toolkit.StringUtils;
+
+import freemarker.template.Template;
+import freemarker.template.TemplateException;
 
 /**
  * <p>
@@ -41,6 +55,7 @@ public abstract class AbstractTemplateEngine {
      */
     private ConfigBuilder configBuilder;
 
+
     /**
      * <p>
      * 模板引擎初始化
@@ -51,13 +66,73 @@ public abstract class AbstractTemplateEngine {
         return this;
     }
 
+
     /**
      * <p>
      * 输出 java xml 文件
      * </p>
      */
-    public abstract AbstractTemplateEngine batchOutput();
+    public AbstractTemplateEngine batchOutput() {
+        try {
+            List<TableInfo> tableInfoList = this.getConfigBuilder().getTableInfoList();
+            for (TableInfo tableInfo : tableInfoList) {
+                Map<String, Object> objectMap = this.getObjectMap(tableInfo);
+                String entityName = tableInfo.getEntityName();
+                Map<String, String> pathInfo = this.getConfigBuilder().getPathInfo();
+                String entityFile = String.format((pathInfo.get(ConstVal.ENTITY_PATH) + File.separator + "%s" + this.suffixJavaOrKt()), entityName);
+                String mapperFile = String.format((pathInfo.get(ConstVal.MAPPER_PATH) + File.separator + tableInfo.getMapperName() + this.suffixJavaOrKt()), entityName);
+                String xmlFile = String.format((pathInfo.get(ConstVal.XML_PATH) + File.separator + tableInfo.getXmlName() + ConstVal.XML_SUFFIX), entityName);
+                String serviceFile = String.format((pathInfo.get(ConstVal.SERIVCE_PATH) + File.separator + tableInfo.getServiceName() + this.suffixJavaOrKt()), entityName);
+                String implFile = String.format((pathInfo.get(ConstVal.SERVICEIMPL_PATH) + File.separator + tableInfo.getServiceImplName() + this.suffixJavaOrKt()), entityName);
+                String controllerFile = String.format((pathInfo.get(ConstVal.CONTROLLER_PATH) + File.separator + tableInfo.getControllerName() + this.suffixJavaOrKt()), entityName);
+                TemplateConfig template = this.getConfigBuilder().getTemplate();
+                if (this.isCreate(entityFile)) {
+                    this.writer(objectMap, this.templateFilePath(template.getEntity(this.getConfigBuilder().getGlobalConfig().isKotlin())), mapperFile);
+                }
+                if (this.isCreate(mapperFile)) {
+                    this.writer(objectMap, this.templateFilePath(template.getMapper()), entityFile);
+                }
+                if (this.isCreate(xmlFile)) {
+                    this.writer(objectMap, this.templateFilePath(template.getXml()), xmlFile);
+                }
+                if (this.isCreate(serviceFile)) {
+                    this.writer(objectMap, this.templateFilePath(template.getService()), serviceFile);
+                }
+                if (this.isCreate(implFile)) {
+                    this.writer(objectMap, this.templateFilePath(template.getServiceImpl()), implFile);
+                }
+                if (this.isCreate(controllerFile)) {
+                    this.writer(objectMap, this.templateFilePath(template.getController()), controllerFile);
+                }
+                if (this.getConfigBuilder().getInjectionConfig() != null) {
+                    List<FileOutConfig> focList = this.getConfigBuilder().getInjectionConfig().getFileOutConfigList();
+                    if (CollectionUtils.isNotEmpty(focList)) {
+                        for (FileOutConfig foc : focList) {
+                            if (this.isCreate(foc.outputFile(tableInfo))) {
+                                this.writer(objectMap, foc.getTemplatePath(), foc.outputFile(tableInfo));
+                            }
+                        }
+                    }
+                }
+
+            }
+        } catch (Exception e) {
+            logger.error("无法创建文件,请检查配置信息!", e);
+        }
+        return this;
+    }
+
 
+    /**
+     * <p>
+     * 将模板转化成为文件
+     * </p>
+     *
+     * @param objectMap    渲染对象 MAP 信息
+     * @param templatePath 模板文件
+     * @param outputFile   文件生成的目录
+     */
+    public abstract void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception;
 
     /**
      * <p>
@@ -104,6 +179,78 @@ public abstract class AbstractTemplateEngine {
     }
 
 
+    /**
+     * <p>
+     * 渲染对象 MAP 信息
+     * </p>
+     *
+     * @param tableInfo 表信息对象
+     * @return
+     */
+    public Map<String, Object> getObjectMap(TableInfo tableInfo) {
+        Map<String, Object> objectMap = new HashMap<>();
+        ConfigBuilder config = this.getConfigBuilder();
+        if (config.getStrategyConfig().isControllerMappingHyphenStyle()) {
+            objectMap.put("controllerMappingHyphenStyle", config.getStrategyConfig().isControllerMappingHyphenStyle());
+            objectMap.put("controllerMappingHyphen", StringUtils.camelToHyphen(tableInfo.getEntityPath()));
+        }
+        objectMap.put("restControllerStyle", config.getStrategyConfig().isRestControllerStyle());
+        objectMap.put("package", config.getPackageInfo());
+        GlobalConfig globalConfig = config.getGlobalConfig();
+        objectMap.put("author", globalConfig.getAuthor());
+        objectMap.put("idType", globalConfig.getIdType() == null ? null : globalConfig.getIdType().toString());
+        objectMap.put("logicDeleteFieldName", config.getStrategyConfig().getLogicDeleteFieldName());
+        objectMap.put("versionFieldName", config.getStrategyConfig().getVersionFieldName());
+        objectMap.put("activeRecord", globalConfig.isActiveRecord());
+        objectMap.put("kotlin", globalConfig.isKotlin());
+        objectMap.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
+        objectMap.put("table", tableInfo);
+        objectMap.put("enableCache", globalConfig.isEnableCache());
+        objectMap.put("baseResultMap", globalConfig.isBaseResultMap());
+        objectMap.put("baseColumnList", globalConfig.isBaseColumnList());
+        objectMap.put("entity", tableInfo.getEntityName());
+        objectMap.put("entityColumnConstant", config.getStrategyConfig().isEntityColumnConstant());
+        objectMap.put("entityBuilderModel", config.getStrategyConfig().isEntityBuilderModel());
+        objectMap.put("entityLombokModel", config.getStrategyConfig().isEntityLombokModel());
+        objectMap.put("entityBooleanColumnRemoveIsPrefix", config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix());
+        objectMap.put("superEntityClass", this.getSuperClassName(config.getSuperEntityClass()));
+        objectMap.put("superMapperClassPackage", config.getSuperMapperClass());
+        objectMap.put("superMapperClass", this.getSuperClassName(config.getSuperMapperClass()));
+        objectMap.put("superServiceClassPackage", config.getSuperServiceClass());
+        objectMap.put("superServiceClass", this.getSuperClassName(config.getSuperServiceClass()));
+        objectMap.put("superServiceImplClassPackage", config.getSuperServiceImplClass());
+        objectMap.put("superServiceImplClass", this.getSuperClassName(config.getSuperServiceImplClass()));
+        objectMap.put("superControllerClassPackage", config.getSuperControllerClass());
+        objectMap.put("superControllerClass", this.getSuperClassName(config.getSuperControllerClass()));
+        return objectMap;
+    }
+
+
+    /**
+     * 获取类名
+     *
+     * @param classPath
+     * @return
+     */
+    private String getSuperClassName(String classPath) {
+        if (StringUtils.isEmpty(classPath)) {
+            return null;
+        }
+        return classPath.substring(classPath.lastIndexOf(".") + 1);
+    }
+
+
+    /**
+     * <p>
+     * 模板真实文件路径
+     * </p>
+     *
+     * @param filePath 文件路径
+     * @return
+     */
+    public abstract String templateFilePath(String filePath);
+
+
     /**
      * 检测文件是否存在
      *
@@ -114,6 +261,7 @@ public abstract class AbstractTemplateEngine {
         return !file.exists() || this.getConfigBuilder().getGlobalConfig().isFileOverride();
     }
 
+
     /**
      * 文件后缀
      */
@@ -121,6 +269,7 @@ public abstract class AbstractTemplateEngine {
         return this.getConfigBuilder().getGlobalConfig().isKotlin() ? ConstVal.KT_SUFFIX : ConstVal.JAVA_SUFFIX;
     }
 
+
     public ConfigBuilder getConfigBuilder() {
         return configBuilder;
     }

+ 43 - 136
mybatis-plus-generate/src/main/java/com/baomidou/mybatisplus/generator/engine/FreemarkerTemplateEngine.java

@@ -1,12 +1,29 @@
+/**
+ * Copyright (c) 2011-2020, 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.baomidou.mybatisplus.generator.engine;
 
 import com.baomidou.mybatisplus.generator.config.ConstVal;
 import com.baomidou.mybatisplus.generator.config.FileOutConfig;
 import com.baomidou.mybatisplus.generator.config.GlobalConfig;
+import com.baomidou.mybatisplus.generator.config.TemplateConfig;
 import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 import com.baomidou.mybatisplus.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.toolkit.StringUtils;
+
 import freemarker.template.Configuration;
 import freemarker.template.Template;
 import freemarker.template.TemplateException;
@@ -23,149 +40,39 @@ import java.util.List;
 import java.util.Map;
 
 /**
- * @author nieqiurong 2018/1/11.
+ * <p>
+ * Freemarker 模板引擎实现文件输出
+ * </p>
+ *
+ * @author nieqiurong
+ * @since 2018-01-11
  */
 public class FreemarkerTemplateEngine extends AbstractTemplateEngine {
-    
+
     private Configuration configuration;
-    
+
     @Override
-    public AbstractTemplateEngine batchOutput() {
-        try {
-            configuration = new Configuration(Configuration.VERSION_2_3_0);
-            configuration.setDefaultEncoding(ConstVal.UTF8);
-            configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, "/");
-            List<TableInfo> tableInfoList = this.getConfigBuilder().getTableInfoList();
-            for (TableInfo tableInfo : tableInfoList) {
-                Map<String,Object> objectMap = this.getVelocityContextInfo(tableInfo);
-                String entityName = tableInfo.getEntityName();
-                Map<String, String> pathInfo = this.getConfigBuilder().getPathInfo();
-                String entityFile = String.format((pathInfo.get(ConstVal.ENTITY_PATH) + File.separator + "%s" + this.suffixJavaOrKt()), entityName);
-                String mapperFile = String.format((pathInfo.get(ConstVal.MAPPER_PATH) + File.separator + tableInfo.getMapperName() + this.suffixJavaOrKt()), entityName);
-                String xmlFile = String.format((pathInfo.get(ConstVal.XML_PATH) + File.separator + tableInfo.getXmlName() + ConstVal.XML_SUFFIX), entityName);
-                String serviceFile = String.format((pathInfo.get(ConstVal.SERIVCE_PATH) + File.separator + tableInfo.getServiceName() + this.suffixJavaOrKt()), entityName);
-                String implFile = String.format((pathInfo.get(ConstVal.SERVICEIMPL_PATH) + File.separator + tableInfo.getServiceImplName() + this.suffixJavaOrKt()), entityName);
-                String controllerFile = String.format((pathInfo.get(ConstVal.CONTROLLER_PATH) + File.separator + tableInfo.getControllerName() + this.suffixJavaOrKt()), entityName);
-                if (isCreate(entityFile)) {
-                    if(this.getConfigBuilder().getGlobalConfig().isKotlin()){
-                        this.writer(configuration.getTemplate(templateFilePath(ConstVal.TEMPLATE_ENTITY_KT)),objectMap,entityFile);
-                    }else{
-                        this.writer(configuration.getTemplate(templateFilePath(ConstVal.TEMPLATE_ENTITY_JAVA)),objectMap,entityFile);
-                    }
-                }
-                if (isCreate(mapperFile)) {
-                    this.writer(configuration.getTemplate(templateFilePath(ConstVal.TEMPLATE_MAPPER)),objectMap,mapperFile);
-                }
-                if (isCreate(xmlFile)) {
-                    this.writer(configuration.getTemplate(templateFilePath(ConstVal.TEMPLATE_XML)),objectMap,xmlFile);
-                }
-                if (isCreate(serviceFile)) {
-                    this.writer(configuration.getTemplate(templateFilePath(ConstVal.TEMPLATE_SERVICE)),objectMap,serviceFile);
-                }
-                if (isCreate(implFile)) {
-                    this.writer(configuration.getTemplate(templateFilePath(ConstVal.TEMPLATE_SERVICEIMPL)),objectMap,implFile);
-                }
-                if (isCreate(controllerFile)) {
-                    this.writer(configuration.getTemplate(templateFilePath(ConstVal.TEMPLATE_CONTROLLER)),objectMap,controllerFile);
-                }
-                if (this.getConfigBuilder().getInjectionConfig() != null) {
-                    List<FileOutConfig> focList = this.getConfigBuilder().getInjectionConfig().getFileOutConfigList();
-                    if (CollectionUtils.isNotEmpty(focList)) {
-                        for (FileOutConfig foc : focList) {
-                            if (isCreate(foc.outputFile(tableInfo))) {
-                                this.writer(configuration.getTemplate(foc.getTemplatePath()),objectMap,foc.outputFile(tableInfo));
-                            }
-                        }
-                    }
-                }
-            
-            }
-        } catch (IOException e) {
-            logger.error("无法创建文件,请检查配置信息!", e);
-        } catch (TemplateException e) {
-            e.printStackTrace();
-        }
+    public FreemarkerTemplateEngine init(ConfigBuilder configBuilder) {
+        super.init(configBuilder);
+        configuration = new Configuration(Configuration.VERSION_2_3_0);
+        configuration.setDefaultEncoding(ConstVal.UTF8);
+        configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, "/");
         return this;
     }
-    
-    /**
-     * 获取模板引擎渲染上下文信息
-     * @param tableInfo 表信息对象
-     * @return
-     */
-    public Map<String,Object> getVelocityContextInfo(TableInfo tableInfo) {
-        Map<String,Object>  objectMap = new HashMap<>();
-        ConfigBuilder config = this.getConfigBuilder();
-        if (config.getStrategyConfig().isControllerMappingHyphenStyle()) {
-            objectMap.put("controllerMappingHyphenStyle", config.getStrategyConfig().isControllerMappingHyphenStyle());
-            objectMap.put("controllerMappingHyphen", StringUtils.camelToHyphen(tableInfo.getEntityPath()));
-        }
-        objectMap.put("restControllerStyle", config.getStrategyConfig().isRestControllerStyle());
-        objectMap.put("package", config.getPackageInfo());
-        GlobalConfig globalConfig = config.getGlobalConfig();
-        objectMap.put("author", globalConfig.getAuthor());
-        objectMap.put("idType", globalConfig.getIdType() == null ? null : globalConfig.getIdType().toString());
-        objectMap.put("logicDeleteFieldName", config.getStrategyConfig().getLogicDeleteFieldName());
-        objectMap.put("versionFieldName", config.getStrategyConfig().getVersionFieldName());
-        objectMap.put("activeRecord", globalConfig.isActiveRecord());
-        objectMap.put("kotlin", globalConfig.isKotlin());
-        objectMap.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
-        objectMap.put("table", tableInfo);
-        objectMap.put("enableCache", globalConfig.isEnableCache());
-        objectMap.put("baseResultMap", globalConfig.isBaseResultMap());
-        objectMap.put("baseColumnList", globalConfig.isBaseColumnList());
-        objectMap.put("entity", tableInfo.getEntityName());
-        objectMap.put("entityColumnConstant", config.getStrategyConfig().isEntityColumnConstant());
-        objectMap.put("entityBuilderModel", config.getStrategyConfig().isEntityBuilderModel());
-        objectMap.put("entityLombokModel", config.getStrategyConfig().isEntityLombokModel());
-        objectMap.put("entityBooleanColumnRemoveIsPrefix", config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix());
-        objectMap.put("superEntityClass", this.getSuperClassName(config.getSuperEntityClass()));
-        objectMap.put("superMapperClassPackage", config.getSuperMapperClass());
-        objectMap.put("superMapperClass", this.getSuperClassName(config.getSuperMapperClass()));
-        objectMap.put("superServiceClassPackage", config.getSuperServiceClass());
-        objectMap.put("superServiceClass", this.getSuperClassName(config.getSuperServiceClass()));
-        objectMap.put("superServiceImplClassPackage", config.getSuperServiceImplClass());
-        objectMap.put("superServiceImplClass", this.getSuperClassName(config.getSuperServiceImplClass()));
-        objectMap.put("superControllerClassPackage", config.getSuperControllerClass());
-        objectMap.put("superControllerClass", this.getSuperClassName(config.getSuperControllerClass()));
-        return objectMap;
-    }
-    
-    
-    /**
-     * 获取类名
-     * @param classPath
-     * @return
-     */
-    private String getSuperClassName(String classPath) {
-        if (StringUtils.isEmpty(classPath)) {
-            return null;
-        }
-        return classPath.substring(classPath.lastIndexOf(".") + 1);
-    }
-    
-    /**
-     * 文件写出
-     * @param template
-     * @param dataModel
-     * @param fileName
-     * @throws IOException
-     * @throws TemplateException
-     */
-    private void writer(Template template, Object dataModel, String fileName) throws IOException, TemplateException {
-        File file = new File(fileName);
-        Writer writer = new OutputStreamWriter(new FileOutputStream(file), ConstVal.UTF8);
-        template.process(dataModel, writer);
+
+
+    @Override
+    public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
+        Template template = configuration.getTemplate(templatePath);
+        FileOutputStream fileOutputStream = new FileOutputStream(new File(outputFile));
+        template.process(objectMap, new OutputStreamWriter(fileOutputStream, ConstVal.UTF8));
+        fileOutputStream.close();
+        logger.debug("模板:" + templatePath + ";  文件:" + outputFile);
     }
-    
-    /**
-     * <p>
-     * 模板真实文件路径加上.ftl
-     * </p>
-     * @param filePath 文件路径
-     * @return
-     */
-    protected String templateFilePath(String filePath) {
+
+
+    @Override
+    public String templateFilePath(String filePath) {
         StringBuilder fp = new StringBuilder();
         fp.append(filePath).append(".ftl");
         return fp.toString();

+ 10 - 152
mybatis-plus-generate/src/main/java/com/baomidou/mybatisplus/generator/engine/VelocityTemplateEngine.java

@@ -67,167 +67,25 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
         return this;
     }
 
-    @Override
-    public VelocityTemplateEngine batchOutput() {
-        try {
-            List<TableInfo> tableInfoList = this.getConfigBuilder().getTableInfoList();
-            for (TableInfo tableInfo : tableInfoList) {
-                VelocityContext context = this.getVelocityContextInfo(tableInfo);
-                String entityName = tableInfo.getEntityName();
-                Map<String, String> pathInfo = this.getConfigBuilder().getPathInfo();
-                String entityFile = String.format((pathInfo.get(ConstVal.ENTITY_PATH) + File.separator + "%s" + this.suffixJavaOrKt()), entityName);
-                String mapperFile = String.format((pathInfo.get(ConstVal.MAPPER_PATH) + File.separator + tableInfo.getMapperName() + this.suffixJavaOrKt()), entityName);
-                String xmlFile = String.format((pathInfo.get(ConstVal.XML_PATH) + File.separator + tableInfo.getXmlName() + ConstVal.XML_SUFFIX), entityName);
-                String serviceFile = String.format((pathInfo.get(ConstVal.SERIVCE_PATH) + File.separator + tableInfo.getServiceName() + this.suffixJavaOrKt()), entityName);
-                String implFile = String.format((pathInfo.get(ConstVal.SERVICEIMPL_PATH) + File.separator + tableInfo.getServiceImplName() + this.suffixJavaOrKt()), entityName);
-                String controllerFile = String.format((pathInfo.get(ConstVal.CONTROLLER_PATH) + File.separator + tableInfo.getControllerName() + this.suffixJavaOrKt()), entityName);
-                TemplateConfig template = this.getConfigBuilder().getTemplate();
-                // 根据override标识来判断是否需要创建文件
-                if (isCreate(entityFile)) {
-                    this.vmToFile(context, this.templateFilePath(template.getEntity(this.getConfigBuilder()
-                        .getGlobalConfig().isKotlin())), entityFile);
-                }
-                if (isCreate(mapperFile)) {
-                    this.vmToFile(context, this.templateFilePath(template.getMapper()), mapperFile);
-                }
-                if (isCreate(xmlFile)) {
-                    this.vmToFile(context, this.templateFilePath(template.getXml()), xmlFile);
-                }
-                if (isCreate(serviceFile)) {
-                    this.vmToFile(context, this.templateFilePath(template.getService()), serviceFile);
-                }
-                if (isCreate(implFile)) {
-                    this.vmToFile(context, this.templateFilePath(template.getServiceImpl()), implFile);
-                }
-                if (isCreate(controllerFile)) {
-                    this.vmToFile(context, this.templateFilePath(template.getController()), controllerFile);
-                }
-                if (this.getConfigBuilder().getInjectionConfig() != null) {
-                    /**
-                     * 输出自定义文件内容
-                     */
-                    List<FileOutConfig> focList = this.getConfigBuilder().getInjectionConfig().getFileOutConfigList();
-                    if (CollectionUtils.isNotEmpty(focList)) {
-                        for (FileOutConfig foc : focList) {
-                            // 判断自定义文件是否存在
-                            if (isCreate(foc.outputFile(tableInfo))) {
-                                this.vmToFile(context, foc.getTemplatePath(), foc.outputFile(tableInfo));
-                            }
-                        }
-                    }
-                }
-
-            }
-        } catch (IOException e) {
-            logger.error("无法创建文件,请检查配置信息!", e);
-        }
-        return this;
-    }
-
-    /**
-     * <p>
-     * 模板真实文件路径加上 .vm
-     * </p>
-     *
-     * @param filePath 文件路径
-     * @return
-     */
-    protected String templateFilePath(String filePath) {
-        StringBuilder fp = new StringBuilder();
-        fp.append(filePath).append(".vm");
-        return fp.toString();
-    }
-
-    /**
-     * <p>
-     * 获取模板引擎渲染上下文信息
-     * </p>
-     *
-     * @param tableInfo 表信息对象
-     * @return
-     */
-    public VelocityContext getVelocityContextInfo(TableInfo tableInfo) {
-        VelocityContext ctx = new VelocityContext();
-        ConfigBuilder config = this.getConfigBuilder();
-        // RequestMapping 连字符风格 user-info
-        if (config.getStrategyConfig().isControllerMappingHyphenStyle()) {
-            ctx.put("controllerMappingHyphenStyle", config.getStrategyConfig().isControllerMappingHyphenStyle());
-            ctx.put("controllerMappingHyphen", StringUtils.camelToHyphen(tableInfo.getEntityPath()));
-        }
-        ctx.put("restControllerStyle", config.getStrategyConfig().isRestControllerStyle());
-        ctx.put("package", config.getPackageInfo());
-        GlobalConfig globalConfig = config.getGlobalConfig();
-        ctx.put("author", globalConfig.getAuthor());
-        ctx.put("idType", globalConfig.getIdType() == null ? null : globalConfig.getIdType().toString());
-        ctx.put("logicDeleteFieldName", config.getStrategyConfig().getLogicDeleteFieldName());
-        ctx.put("versionFieldName", config.getStrategyConfig().getVersionFieldName());
-        ctx.put("activeRecord", globalConfig.isActiveRecord());
-        ctx.put("kotlin", globalConfig.isKotlin());
-        ctx.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
-        ctx.put("table", tableInfo);
-        ctx.put("enableCache", globalConfig.isEnableCache());
-        ctx.put("baseResultMap", globalConfig.isBaseResultMap());
-        ctx.put("baseColumnList", globalConfig.isBaseColumnList());
-        ctx.put("entity", tableInfo.getEntityName());
-        ctx.put("entityColumnConstant", config.getStrategyConfig().isEntityColumnConstant());
-        ctx.put("entityBuilderModel", config.getStrategyConfig().isEntityBuilderModel());
-        ctx.put("entityLombokModel", config.getStrategyConfig().isEntityLombokModel());
-        ctx.put("entityBooleanColumnRemoveIsPrefix", config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix());
-        ctx.put("superEntityClass", this.getSuperClassName(config.getSuperEntityClass()));
-        ctx.put("superMapperClassPackage", config.getSuperMapperClass());
-        ctx.put("superMapperClass", this.getSuperClassName(config.getSuperMapperClass()));
-        ctx.put("superServiceClassPackage", config.getSuperServiceClass());
-        ctx.put("superServiceClass", this.getSuperClassName(config.getSuperServiceClass()));
-        ctx.put("superServiceImplClassPackage", config.getSuperServiceImplClass());
-        ctx.put("superServiceImplClass", this.getSuperClassName(config.getSuperServiceImplClass()));
-        ctx.put("superControllerClassPackage", config.getSuperControllerClass());
-        ctx.put("superControllerClass", this.getSuperClassName(config.getSuperControllerClass()));
-        return ctx;
-    }
 
-
-    /**
-     * <p>
-     * 获取类名
-     * </p>
-     *
-     * @param classPath
-     * @return
-     */
-    private String getSuperClassName(String classPath) {
-        if (StringUtils.isEmpty(classPath)) {
-            return null;
-        }
-        return classPath.substring(classPath.lastIndexOf(".") + 1);
-    }
-
-    /**
-     * <p>
-     * 将模板转化成为文件
-     * </p>
-     *
-     * @param context      内容对象
-     * @param templatePath 模板文件
-     * @param outputFile   文件生成的目录
-     */
-    private void vmToFile(VelocityContext context, String templatePath, String outputFile) throws IOException {
+    @Override
+    public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
         if (StringUtils.isEmpty(templatePath)) {
             return;
         }
         Template template = velocityEngine.getTemplate(templatePath, ConstVal.UTF8);
-        File file = new File(outputFile);
-        if (!file.getParentFile().exists()) {
-            // 如果文件所在的目录不存在,则创建目录
-            if (!file.getParentFile().mkdirs()) {
-                logger.debug("创建文件所在的目录失败!");
-                return;
-            }
-        }
         FileOutputStream fos = new FileOutputStream(outputFile);
         BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, ConstVal.UTF8));
-        template.merge(context, writer);
+        template.merge(new VelocityContext(objectMap), writer);
         writer.close();
         logger.debug("模板:" + templatePath + ";  文件:" + outputFile);
     }
 
+
+    @Override
+    public String templateFilePath(String filePath) {
+        StringBuilder fp = new StringBuilder();
+        fp.append(filePath).append(".vm");
+        return fp.toString();
+    }
 }

+ 40 - 0
mybatis-plus-generate/src/test/java/com/baomidou/mybatisplus/test/generator/GeneratorTest.java

@@ -0,0 +1,40 @@
+package com.baomidou.mybatisplus.test.generator;
+
+import java.util.Scanner;
+
+
+/**
+ * <p>
+ * Generator test
+ * </p>
+ *
+ * @author hubin
+ * @Date 2018-01-11
+ */
+public class GeneratorTest {
+
+    /**
+     * <p>
+     * 读取控制台内容
+     * </p>
+     */
+    public static int scanner() {
+        Scanner scanner = new Scanner(System.in);
+        StringBuilder help = new StringBuilder();
+        help.append(" !!代码生成, 输入 0 表示使用 Velocity 引擎 !!");
+        help.append("\n对照表:");
+        help.append("\n0 = Velocity 引擎");
+        help.append("\n1 = Freemarker 引擎");
+        help.append("\n请输入:");
+        System.out.println(help.toString());
+        int slt = 0;
+        // 现在有输入数据
+        if (scanner.hasNext()) {
+            String ipt = scanner.next();
+            if ("1".equals(ipt)) {
+                slt = 1;
+            }
+        }
+        return slt;
+    }
+}

+ 104 - 99
mybatis-plus-generate/src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java

@@ -36,6 +36,7 @@ import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
 import com.baomidou.mybatisplus.generator.config.rules.DbType;
 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
+import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
 
 /**
  * <p>
@@ -45,7 +46,7 @@ import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  * @author hubin
  * @date 2016-12-01
  */
-public class MysqlGenerator {
+public class MysqlGenerator extends GeneratorTest {
 
     /**
      * <p>
@@ -53,117 +54,121 @@ public class MysqlGenerator {
      * </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("/develop/code/")//输出目录
-                        .setFileOverride(true)// 是否覆盖文件
-                        .setActiveRecord(true)// 开启 activeRecord 模式
-                        .setEnableCache(false)// XML 二级缓存
-                        .setBaseResultMap(true)// XML ResultMap
-                        .setBaseColumnList(true)// XML columList
-                        //.setKotlin(true) 是否生成 kotlin 代码
-                        .setAuthor("Yanghu")
-                // 自定义文件命名,注意 %s 会自动填充表实体属性!
-                // .setMapperName("%sDao")
-                // .setXmlName("%sDao")
-                // .setServiceName("MP%sService")
-                // .setServiceImplName("%sServiceDiy")
-                // .setControllerName("%sAction")
+            // 全局配置
+            new GlobalConfig()
+                .setOutputDir("/develop/code/")//输出目录
+                .setFileOverride(true)// 是否覆盖文件
+                .setActiveRecord(true)// 开启 activeRecord 模式
+                .setEnableCache(false)// XML 二级缓存
+                .setBaseResultMap(true)// XML ResultMap
+                .setBaseColumnList(true)// XML columList
+                //.setKotlin(true) 是否生成 kotlin 代码
+                .setAuthor("Yanghu")
+            // 自定义文件命名,注意 %s 会自动填充表实体属性!
+            // .setMapperName("%sDao")
+            // .setXmlName("%sDao")
+            // .setServiceName("MP%sService")
+            // .setServiceImplName("%sServiceDiy")
+            // .setControllerName("%sAction")
         ).setDataSource(
-                // 数据源配置
-                new DataSourceConfig()
-                        .setDbType(DbType.MYSQL)// 数据库类型
-                        .setTypeConvert(new MySqlTypeConvert() {
-                            // 自定义数据库表字段类型转换【可选】
-                            @Override
-                            public DbColumnType processTypeConvert(String fieldType) {
-                                System.out.println("转换类型:" + fieldType);
-                                // if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
-                                //    return DbColumnType.BOOLEAN;
-                                // }
-                                return super.processTypeConvert(fieldType);
-                            }
-                        })
-                        .setDriverName("com.mysql.jdbc.Driver")
-                        .setUsername("root")
-                        .setPassword("123456")
-                        .setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8")
+            // 数据源配置
+            new DataSourceConfig()
+                .setDbType(DbType.MYSQL)// 数据库类型
+                .setTypeConvert(new MySqlTypeConvert() {
+                    // 自定义数据库表字段类型转换【可选】
+                    @Override
+                    public DbColumnType processTypeConvert(String fieldType) {
+                        System.out.println("转换类型:" + fieldType);
+                        // if ( fieldType.toLowerCase().contains( "tinyint" ) ) {
+                        //    return DbColumnType.BOOLEAN;
+                        // }
+                        return super.processTypeConvert(fieldType);
+                    }
+                })
+                .setDriverName("com.mysql.jdbc.Driver")
+                .setUsername("root")
+                .setPassword("123456")
+                .setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8")
         ).setStrategy(
-                // 策略配置
-                new StrategyConfig()
-                        // .setCapitalMode(true)// 全局大写命名
-                        // .setDbColumnUnderline(true)//全局下划线命名
-                        .setTablePrefix(new String[]{"bmd_", "mp_"})// 此处可以修改为您的表前缀
-                        .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
-                        // .setInclude(new String[] { "user" }) // 需要生成的表
-                        // .setExclude(new String[]{"test"}) // 排除生成的表
-                        // 自定义实体父类
-                        // .setSuperEntityClass("com.baomidou.demo.TestEntity")
-                        // 自定义实体,公共字段
-                        .setSuperEntityColumns(new String[]{"test_id"})
-                        .setTableFillList(tableFillList)
-                // 自定义 mapper 父类
-                // .setSuperMapperClass("com.baomidou.demo.TestMapper")
-                // 自定义 service 父类
-                // .setSuperServiceClass("com.baomidou.demo.TestService")
-                // 自定义 service 实现类父类
-                // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl")
-                // 自定义 controller 父类
-                // .setSuperControllerClass("com.baomidou.demo.TestController")
-                // 【实体】是否生成字段常量(默认 false)
-                // public static final String ID = "test_id";
-                // .setEntityColumnConstant(true)
-                // 【实体】是否为构建者模型(默认 false)
-                // public User setName(String name) {this.name = name; return this;}
-                // .setEntityBuilderModel(true)
-                // 【实体】是否为lombok模型(默认 false)<a href="https://projectlombok.org/">document</a>
-                // .setEntityLombokModel(true)
-                // Boolean类型字段是否移除is前缀处理
-                // .setEntityBooleanColumnRemoveIsPrefix(true)
-                // .setRestControllerStyle(true)
-                // .setControllerMappingHyphenStyle(true)
+            // 策略配置
+            new StrategyConfig()
+                // .setCapitalMode(true)// 全局大写命名
+                // .setDbColumnUnderline(true)//全局下划线命名
+                .setTablePrefix(new String[]{"bmd_", "mp_"})// 此处可以修改为您的表前缀
+                .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
+                // .setInclude(new String[] { "user" }) // 需要生成的表
+                // .setExclude(new String[]{"test"}) // 排除生成的表
+                // 自定义实体父类
+                // .setSuperEntityClass("com.baomidou.demo.TestEntity")
+                // 自定义实体,公共字段
+                .setSuperEntityColumns(new String[]{"test_id"})
+                .setTableFillList(tableFillList)
+            // 自定义 mapper 父类
+            // .setSuperMapperClass("com.baomidou.demo.TestMapper")
+            // 自定义 service 父类
+            // .setSuperServiceClass("com.baomidou.demo.TestService")
+            // 自定义 service 实现类父类
+            // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl")
+            // 自定义 controller 父类
+            // .setSuperControllerClass("com.baomidou.demo.TestController")
+            // 【实体】是否生成字段常量(默认 false)
+            // public static final String ID = "test_id";
+            // .setEntityColumnConstant(true)
+            // 【实体】是否为构建者模型(默认 false)
+            // public User setName(String name) {this.name = name; return this;}
+            // .setEntityBuilderModel(true)
+            // 【实体】是否为lombok模型(默认 false)<a href="https://projectlombok.org/">document</a>
+            // .setEntityLombokModel(true)
+            // Boolean类型字段是否移除is前缀处理
+            // .setEntityBooleanColumnRemoveIsPrefix(true)
+            // .setRestControllerStyle(true)
+            // .setControllerMappingHyphenStyle(true)
         ).setPackageInfo(
-                // 包配置
-                new PackageConfig()
-                        .setModuleName("test")
-                        .setParent("com.baomidou")// 自定义包路径
-                        .setController("controller")// 这里是控制器包名,默认 web
+            // 包配置
+            new PackageConfig()
+                .setModuleName("test")
+                .setParent("com.baomidou")// 自定义包路径
+                .setController("controller")// 这里是控制器包名,默认 web
         ).setCfg(
-                // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
-                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.vm") {
-                    // 自定义输出文件目录
-                    @Override
-                    public String outputFile(TableInfo tableInfo) {
-                        return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
-                    }
-                }))
+            // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
+            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 "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
+                }
+            }))
         ).setTemplate(
-                // 关闭默认 xml 生成,调整生成 至 根目录
-                new TemplateConfig().setXml(null)
-                // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
-                // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置:
-                // .setController("...");
-                // .setEntity("...");
-                // .setMapper("...");
-                // .setXml("...");
-                // .setService("...");
-                // .setServiceImpl("...");
+            // 关闭默认 xml 生成,调整生成 至 根目录
+            new TemplateConfig().setXml(null)
+            // 自定义模板配置,模板可以参考源码 /mybatis-plus/src/main/resources/template 使用 copy
+            // 至您项目 src/main/resources/template 目录下,模板名称也可自定义如下配置:
+            // .setController("...");
+            // .setEntity("...");
+            // .setMapper("...");
+            // .setXml("...");
+            // .setService("...");
+            // .setServiceImpl("...");
         );
-
         // 执行生成
+        if (1 == result) {
+            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
+        }
         mpg.execute();
 
         // 打印注入设置,这里演示模板里面怎么获取注入内容【可无】

+ 9 - 2
mybatis-plus-generate/src/test/java/com/baomidou/mybatisplus/test/generator/PostgreSQLGenerator.java

@@ -4,6 +4,7 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.Scanner;
 
 import com.baomidou.mybatisplus.generator.AutoGenerator;
 import com.baomidou.mybatisplus.generator.InjectionConfig;
@@ -17,6 +18,7 @@ import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
 import com.baomidou.mybatisplus.generator.config.rules.DbType;
 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
+import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
 
 /**
  * <p>
@@ -26,9 +28,10 @@ import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  * @author nieqiurong
  * @Date 2016/12/25
  */
-public class PostgreSQLGenerator {
+public class PostgreSQLGenerator extends GeneratorTest {
 
     public static void main(String[] args) {
+        int result = scanner();
         AutoGenerator mpg = new AutoGenerator();
 
         // 全局配置
@@ -113,7 +116,7 @@ public class PostgreSQLGenerator {
             }
         };
         List<FileOutConfig> focList = new ArrayList<>();
-        focList.add(new FileOutConfig("/templates/entity.java.vm") {
+        focList.add(new FileOutConfig("/templates/entity.java" + ((1 == result) ? ".ftl" : ".vm")) {
             @Override
             public String outputFile(TableInfo tableInfo) {
                 // 自定义输入文件名称
@@ -133,7 +136,11 @@ public class PostgreSQLGenerator {
         // tc.setService("...");
         // tc.setServiceImpl("...");
         // mpg.setTemplate(tc);
+
         // 执行生成
+        if (1 == result) {
+            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
+        }
         mpg.execute();
         // 打印注入设置
         System.err.println(mpg.getCfg().getMap().get("abc"));

+ 7 - 2
mybatis-plus-generate/src/test/java/com/baomidou/mybatisplus/test/generator/SQLServerGenerator.java

@@ -17,6 +17,7 @@ import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
 import com.baomidou.mybatisplus.generator.config.rules.DbType;
 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
+import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
 
 /**
  * <p>
@@ -26,9 +27,10 @@ import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  * @author nieqiurong
  * @Date 2016/12/25
  */
-public class SQLServerGenerator {
+public class SQLServerGenerator extends GeneratorTest {
 
     public static void main(String[] args) {
+        int result = scanner();
         AutoGenerator mpg = new AutoGenerator();
 
         // 全局配置
@@ -112,7 +114,7 @@ public class SQLServerGenerator {
             }
         };
         List<FileOutConfig> focList = new ArrayList<>();
-        focList.add(new FileOutConfig("/templates/entity.java.vm") {
+        focList.add(new FileOutConfig("/templates/entity.java" + ((1 == result) ? ".ftl" : ".vm")) {
             @Override
             public String outputFile(TableInfo tableInfo) {
                 // 自定义输入文件名称
@@ -133,6 +135,9 @@ public class SQLServerGenerator {
         // tc.setServiceImpl("...");
         // mpg.setTemplate(tc);
         // 执行生成
+        if (1 == result) {
+            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
+        }
         mpg.execute();
         // 打印注入设置
         System.err.println(mpg.getCfg().getMap().get("abc"));