Browse Source

修复代码生成器>字段前缀导致的bug

yuxiaobin 7 years ago
parent
commit
047d6eab83

+ 4 - 1
mybatis-plus-core/src/test/resources/h2/spring-test-h2-mvc.xml

@@ -36,11 +36,14 @@
         </property>
         </property>
     </bean>
     </bean>
 
 
+	<bean id="mybatisMapWrapperFactory" class="com.baomidou.mybatisplus.MybatisMapWrapperFactory"/>
+
     <bean id="mybatisConfig" class="com.baomidou.mybatisplus.MybatisConfiguration">
     <bean id="mybatisConfig" class="com.baomidou.mybatisplus.MybatisConfiguration">
         <property name="mapUnderscoreToCamelCase" value="true"/>
         <property name="mapUnderscoreToCamelCase" value="true"/>
         <property name="jdbcTypeForNull">
         <property name="jdbcTypeForNull">
             <util:constant static-field="org.apache.ibatis.type.JdbcType.NULL"/>
             <util:constant static-field="org.apache.ibatis.type.JdbcType.NULL"/>
         </property>
         </property>
+		<property name="objectWrapperFactory" ref="mybatisMapWrapperFactory"/>
     </bean>
     </bean>
 
 
     <bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
     <bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
@@ -72,4 +75,4 @@
     <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         <property name="basePackage" value="com.baomidou.mybatisplus.test.h2.entity.mapper"/>
         <property name="basePackage" value="com.baomidou.mybatisplus.test.h2.entity.mapper"/>
     </bean>
     </bean>
-</beans>
+</beans>

+ 1 - 0
mybatis-plus-generate/build.gradle

@@ -8,4 +8,5 @@ dependencies {
     testCompile rootProject.ext.dependencies["mysql"]
     testCompile rootProject.ext.dependencies["mysql"]
     testCompile rootProject.ext.dependencies["logback-classic"]
     testCompile rootProject.ext.dependencies["logback-classic"]
     testCompile rootProject.ext.dependencies["velocity"]
     testCompile rootProject.ext.dependencies["velocity"]
+	testCompile rootProject.ext.dependencies["junit"]
 }
 }

+ 18 - 11
mybatis-plus-generate/src/main/java/com/baomidou/mybatisplus/generator/AutoGenerator.java

@@ -20,6 +20,7 @@ import java.io.File;
 import java.io.FileOutputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.IOException;
 import java.io.OutputStreamWriter;
 import java.io.OutputStreamWriter;
+import java.io.Serializable;
 import java.text.SimpleDateFormat;
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashMap;
@@ -34,6 +35,10 @@ import org.apache.velocity.app.VelocityEngine;
 import org.slf4j.Logger;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.slf4j.LoggerFactory;
 
 
+import com.baomidou.mybatisplus.activerecord.Model;
+import com.baomidou.mybatisplus.annotations.TableLogic;
+import com.baomidou.mybatisplus.annotations.TableName;
+import com.baomidou.mybatisplus.annotations.Version;
 import com.baomidou.mybatisplus.generator.config.ConstVal;
 import com.baomidou.mybatisplus.generator.config.ConstVal;
 import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
 import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
 import com.baomidou.mybatisplus.generator.config.FileOutConfig;
 import com.baomidou.mybatisplus.generator.config.FileOutConfig;
@@ -162,25 +167,25 @@ public class AutoGenerator {
             /* ---------- 添加导入包 ---------- */
             /* ---------- 添加导入包 ---------- */
             if (config.getGlobalConfig().isActiveRecord()) {
             if (config.getGlobalConfig().isActiveRecord()) {
                 // 开启 ActiveRecord 模式
                 // 开启 ActiveRecord 模式
-                tableInfo.setImportPackages("com.baomidou.mybatisplus.activerecord.Model");
+                tableInfo.setImportPackages(Model.class.getCanonicalName());
             }
             }
             if (tableInfo.isConvert()) {
             if (tableInfo.isConvert()) {
                 // 表注解
                 // 表注解
-                tableInfo.setImportPackages("com.baomidou.mybatisplus.annotations.TableName");
+                tableInfo.setImportPackages(TableName.class.getCanonicalName());
             }
             }
             if (tableInfo.isLogicDelete(config.getStrategyConfig().getLogicDeleteFieldName())) {
             if (tableInfo.isLogicDelete(config.getStrategyConfig().getLogicDeleteFieldName())) {
                 // 逻辑删除注解
                 // 逻辑删除注解
-                tableInfo.setImportPackages("com.baomidou.mybatisplus.annotations.TableLogic");
+                tableInfo.setImportPackages(TableLogic.class.getCanonicalName());
             }
             }
             if (StringUtils.isNotEmpty(config.getStrategyConfig().getVersionFieldName())) {
             if (StringUtils.isNotEmpty(config.getStrategyConfig().getVersionFieldName())) {
                 // 乐观锁注解
                 // 乐观锁注解
-                tableInfo.setImportPackages("com.baomidou.mybatisplus.annotations.Version");
+                tableInfo.setImportPackages(Version.class.getCanonicalName());
             }
             }
             if (StringUtils.isNotEmpty(config.getSuperEntityClass())) {
             if (StringUtils.isNotEmpty(config.getSuperEntityClass())) {
                 // 父实体
                 // 父实体
                 tableInfo.setImportPackages(config.getSuperEntityClass());
                 tableInfo.setImportPackages(config.getSuperEntityClass());
             } else {
             } else {
-                tableInfo.setImportPackages("java.io.Serializable");
+                tableInfo.setImportPackages(Serializable.class.getCanonicalName());
             }
             }
             // Boolean类型is前缀处理
             // Boolean类型is前缀处理
             if (config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix()) {
             if (config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix()) {
@@ -201,16 +206,18 @@ public class AutoGenerator {
 
 
             ctx.put("restControllerStyle", config.getStrategyConfig().isRestControllerStyle());
             ctx.put("restControllerStyle", config.getStrategyConfig().isRestControllerStyle());
             ctx.put("package", packageInfo);
             ctx.put("package", packageInfo);
-            ctx.put("author", config.getGlobalConfig().getAuthor());
+            GlobalConfig globalConfig = config.getGlobalConfig();
+            ctx.put("author", globalConfig.getAuthor() + "123");
+            ctx.put("idType", globalConfig.getIdType() == null ? null : globalConfig.getIdType().toString());
             ctx.put("logicDeleteFieldName", config.getStrategyConfig().getLogicDeleteFieldName());
             ctx.put("logicDeleteFieldName", config.getStrategyConfig().getLogicDeleteFieldName());
             ctx.put("versionFieldName", config.getStrategyConfig().getVersionFieldName());
             ctx.put("versionFieldName", config.getStrategyConfig().getVersionFieldName());
-            ctx.put("activeRecord", config.getGlobalConfig().isActiveRecord());
-            ctx.put("kotlin", config.getGlobalConfig().isKotlin());
+            ctx.put("activeRecord", globalConfig.isActiveRecord());
+            ctx.put("kotlin", globalConfig.isKotlin());
             ctx.put("date", date);
             ctx.put("date", date);
             ctx.put("table", tableInfo);
             ctx.put("table", tableInfo);
-            ctx.put("enableCache", config.getGlobalConfig().isEnableCache());
-            ctx.put("baseResultMap", config.getGlobalConfig().isBaseResultMap());
-            ctx.put("baseColumnList", config.getGlobalConfig().isBaseColumnList());
+            ctx.put("enableCache", globalConfig.isEnableCache());
+            ctx.put("baseResultMap", globalConfig.isBaseResultMap());
+            ctx.put("baseColumnList", globalConfig.isBaseColumnList());
             ctx.put("entity", tableInfo.getEntityName());
             ctx.put("entity", tableInfo.getEntityName());
             ctx.put("entityColumnConstant", config.getStrategyConfig().isEntityColumnConstant());
             ctx.put("entityColumnConstant", config.getStrategyConfig().isEntityColumnConstant());
             ctx.put("entityBuilderModel", config.getStrategyConfig().isEntityBuilderModel());
             ctx.put("entityBuilderModel", config.getStrategyConfig().isEntityBuilderModel());

+ 15 - 0
mybatis-plus-generate/src/main/java/com/baomidou/mybatisplus/generator/config/GlobalConfig.java

@@ -15,6 +15,8 @@
  */
  */
 package com.baomidou.mybatisplus.generator.config;
 package com.baomidou.mybatisplus.generator.config;
 
 
+import com.baomidou.mybatisplus.enums.IdType;
+
 /**
 /**
  * <p>
  * <p>
  * 全局配置
  * 全局配置
@@ -77,6 +79,19 @@ public class GlobalConfig {
     private String serviceName;
     private String serviceName;
     private String serviceImplName;
     private String serviceImplName;
     private String controllerName;
     private String controllerName;
+    /**
+     * 指定生成的主键的ID类型
+     */
+    private IdType idType;
+
+    public GlobalConfig setIdType(IdType idType) {
+        this.idType = idType;
+        return this;
+    }
+
+    public IdType getIdType() {
+        return idType;
+    }
 
 
     public String getOutputDir() {
     public String getOutputDir() {
         return outputDir;
         return outputDir;

+ 20 - 2
mybatis-plus-generate/src/main/java/com/baomidou/mybatisplus/generator/config/StrategyConfig.java

@@ -15,12 +15,12 @@
  */
  */
 package com.baomidou.mybatisplus.generator.config;
 package com.baomidou.mybatisplus.generator.config;
 
 
+import java.util.List;
+
 import com.baomidou.mybatisplus.generator.config.po.TableFill;
 import com.baomidou.mybatisplus.generator.config.po.TableFill;
 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 import com.baomidou.mybatisplus.toolkit.StringUtils;
 import com.baomidou.mybatisplus.toolkit.StringUtils;
 
 
-import java.util.List;
-
 /**
 /**
  * <p>
  * <p>
  * 策略配置项
  * 策略配置项
@@ -135,6 +135,10 @@ public class StrategyConfig {
      */
      */
     private boolean controllerMappingHyphenStyle = false;
     private boolean controllerMappingHyphenStyle = false;
 
 
+    /**
+     * 是否生成实体时,生成字段注解
+     */
+    private boolean entityTableFieldAnnotationEnable = false;
     /**
     /**
      * 乐观锁属性名称
      * 乐观锁属性名称
      */
      */
@@ -399,4 +403,18 @@ public class StrategyConfig {
     public void setFieldPrefix(String[] fieldPrefix) {
     public void setFieldPrefix(String[] fieldPrefix) {
         this.fieldPrefix = fieldPrefix;
         this.fieldPrefix = fieldPrefix;
     }
     }
+
+    public StrategyConfig fieldPrefix(String... fieldPrefixs) {
+        setFieldPrefix(fieldPrefixs);
+        return this;
+    }
+
+    public StrategyConfig entityTableFieldAnnotationEnable(boolean isEnableAnnotation) {
+        this.entityTableFieldAnnotationEnable = isEnableAnnotation;
+        return this;
+    }
+
+    public boolean isEntityTableFieldAnnotationEnable() {
+        return entityTableFieldAnnotationEnable;
+    }
 }
 }

+ 58 - 11
mybatis-plus-generate/src/main/java/com/baomidou/mybatisplus/generator/config/builder/ConfigBuilder.java

@@ -311,12 +311,14 @@ public class ConfigBuilder {
      * 处理表对应的类名称
      * 处理表对应的类名称
      * </P>
      * </P>
      *
      *
-     * @param tableList   表名称
-     * @param strategy    命名策略
-     * @param tablePrefix
+     * @param tableList 表名称
+     * @param strategy  命名策略
+     * @param config    策略配置项
      * @return 补充完整信息后的表
      * @return 补充完整信息后的表
      */
      */
-    private List<TableInfo> processTable(List<TableInfo> tableList, NamingStrategy strategy, String[] tablePrefix) {
+    private List<TableInfo> processTable(List<TableInfo> tableList, NamingStrategy strategy, StrategyConfig config) {
+        String[] tablePrefix = config.getTablePrefix();
+        String[] fieldPrefix = config.getFieldPrefix();
         for (TableInfo tableInfo : tableList) {
         for (TableInfo tableInfo : tableList) {
             tableInfo.setEntityName(strategyConfig, NamingStrategy.capitalFirst(processName(tableInfo.getName(), strategy, tablePrefix)));
             tableInfo.setEntityName(strategyConfig, NamingStrategy.capitalFirst(processName(tableInfo.getName(), strategy, tablePrefix)));
             if (StringUtils.isNotEmpty(globalConfig.getMapperName())) {
             if (StringUtils.isNotEmpty(globalConfig.getMapperName())) {
@@ -344,10 +346,55 @@ public class ConfigBuilder {
             } else {
             } else {
                 tableInfo.setControllerName(tableInfo.getEntityName() + ConstVal.CONTROLLER);
                 tableInfo.setControllerName(tableInfo.getEntityName() + ConstVal.CONTROLLER);
             }
             }
+            //强制开启字段注解
+            checkTableIdTableFieldAnnotation(config, tableInfo, fieldPrefix);
         }
         }
         return tableList;
         return tableList;
     }
     }
 
 
+    /**
+     * 检查是否有
+     *     {@link com.baomidou.mybatisplus.annotations.TableId}
+     *  {@link com.baomidou.mybatisplus.annotations.TableField}
+     *  注解
+     * @param config
+     * @param tableInfo
+     * @param fieldPrefix
+     */
+    private void checkTableIdTableFieldAnnotation(StrategyConfig config, TableInfo tableInfo, String[] fieldPrefix){
+        boolean importTableFieldAnnotaion = false;
+        boolean importTableIdAnnotaion = false;
+        if (config.isEntityTableFieldAnnotationEnable()) {
+            for (TableField tf : tableInfo.getFields()) {
+                tf.setConvert(true);
+                importTableFieldAnnotaion = true;
+                importTableIdAnnotaion = true;
+            }
+        } else if (fieldPrefix != null && fieldPrefix.length != 0) {
+            for (TableField tf : tableInfo.getFields()) {
+                if (NamingStrategy.isPrefixContained(tf.getName(), fieldPrefix)) {
+                    if (tf.isKeyFlag()) {
+                        importTableIdAnnotaion = true;
+                    }
+                    tf.setConvert(true);
+                    importTableFieldAnnotaion = true;
+                }
+            }
+        }
+        if (importTableFieldAnnotaion) {
+            tableInfo.getImportPackages().add(com.baomidou.mybatisplus.annotations.TableField.class.getCanonicalName());
+        }
+        if (importTableIdAnnotaion) {
+            tableInfo.getImportPackages().add(com.baomidou.mybatisplus.annotations.TableId.class.getCanonicalName());
+        }
+        if(globalConfig.getIdType()!=null){
+            if(!importTableIdAnnotaion){
+                tableInfo.getImportPackages().add(com.baomidou.mybatisplus.annotations.TableId.class.getCanonicalName());
+            }
+            tableInfo.getImportPackages().add(com.baomidou.mybatisplus.enums.IdType.class.getCanonicalName());
+        }
+    }
+
     /**
     /**
      * <p>
      * <p>
      * 获取所有的数据库表信息
      * 获取所有的数据库表信息
@@ -460,7 +507,7 @@ public class ConfigBuilder {
                 e.printStackTrace();
                 e.printStackTrace();
             }
             }
         }
         }
-        return processTable(includeTableList, strategy, config.getTablePrefix());
+        return processTable(includeTableList, strategy, config);
     }
     }
 
 
 
 
@@ -603,27 +650,27 @@ public class ConfigBuilder {
 
 
     /**
     /**
      * <p>
      * <p>
-     * 处理字段名称
+     * 处理表/字段名称
      * </p>
      * </p>
      *
      *
      * @param name
      * @param name
      * @param strategy
      * @param strategy
-     * @param tablePrefix
+     * @param prefix
      * @return 根据策略返回处理后的名称
      * @return 根据策略返回处理后的名称
      */
      */
-    private String processName(String name, NamingStrategy strategy, String[] tablePrefix) {
+    private String processName(String name, NamingStrategy strategy, String[] prefix) {
         boolean removePrefix = false;
         boolean removePrefix = false;
-        if (tablePrefix != null && tablePrefix.length >= 1) {
+        if (prefix != null && prefix.length >= 1) {
             removePrefix = true;
             removePrefix = true;
         }
         }
         String propertyName;
         String propertyName;
         if (removePrefix) {
         if (removePrefix) {
             if (strategy == NamingStrategy.underline_to_camel) {
             if (strategy == NamingStrategy.underline_to_camel) {
                 // 删除前缀、下划线转驼峰
                 // 删除前缀、下划线转驼峰
-                propertyName = NamingStrategy.removePrefixAndCamel(name, tablePrefix);
+                propertyName = NamingStrategy.removePrefixAndCamel(name, prefix);
             } else {
             } else {
                 // 删除前缀
                 // 删除前缀
-                propertyName = NamingStrategy.removePrefix(name, tablePrefix);
+                propertyName = NamingStrategy.removePrefix(name, prefix);
             }
             }
         } else if (strategy == NamingStrategy.underline_to_camel) {
         } else if (strategy == NamingStrategy.underline_to_camel) {
             // 下划线转驼峰
             // 下划线转驼峰

+ 17 - 13
mybatis-plus-generate/src/main/java/com/baomidou/mybatisplus/generator/config/rules/NamingStrategy.java

@@ -66,43 +66,47 @@ public enum NamingStrategy {
     }
     }
 
 
     /**
     /**
-     * 去掉下划线前缀
+     * 去掉指定的前缀
      *
      *
      * @param name
      * @param name
+     * @param prefix
      * @return
      * @return
      */
      */
-    public static String removePrefix(String name) {
+    public static String removePrefix(String name, String... prefix) {
         if (StringUtils.isEmpty(name)) {
         if (StringUtils.isEmpty(name)) {
             return "";
             return "";
         }
         }
-        int idx = name.indexOf(ConstVal.UNDERLINE);
-        if (idx == -1) {
-            return name;
+        if (null != prefix) {
+            for (String pf : prefix) {
+                if (name.toLowerCase().matches("^" + pf.toLowerCase() + ".*")) {
+                    // 判断是否有匹配的前缀,然后截取前缀
+                    // 删除前缀
+                    return name.substring(pf.length());
+                }
+            }
         }
         }
-        return name.substring(idx + 1);
+        return name;
     }
     }
 
 
     /**
     /**
-     * 去掉指定的前缀
+     * 判断是否包含prefix
      *
      *
      * @param name
      * @param name
      * @param prefix
      * @param prefix
      * @return
      * @return
      */
      */
-    public static String removePrefix(String name, String[] prefix) {
+    public static boolean isPrefixContained(String name, String... prefix) {
         if (StringUtils.isEmpty(name)) {
         if (StringUtils.isEmpty(name)) {
-            return "";
+            return false;
         }
         }
         if (null != prefix) {
         if (null != prefix) {
             for (String pf : prefix) {
             for (String pf : prefix) {
                 if (name.toLowerCase().matches("^" + pf.toLowerCase() + ".*")) {
                 if (name.toLowerCase().matches("^" + pf.toLowerCase() + ".*")) {
-                    // 判断是否有匹配的前缀,然后截取前缀
-                    // 删除前缀
-                    return name.substring(pf.length());
+                    return true;
                 }
                 }
             }
             }
         }
         }
-        return name;
+        return false;
     }
     }
 
 
     /**
     /**

+ 32 - 30
mybatis-plus-generate/src/main/resources/templates/entity.java.vm

@@ -40,7 +40,7 @@ public class ${entity} extends Model<${entity}> {
 public class ${entity} implements Serializable {
 public class ${entity} implements Serializable {
 #end
 #end
 
 
-	private static final long serialVersionUID = 1L;
+    private static final long serialVersionUID = 1L;
 
 
 ## ----------  BEGIN 字段循环遍历  ----------
 ## ----------  BEGIN 字段循环遍历  ----------
 #foreach($field in ${table.fields})
 #foreach($field in ${table.fields})
@@ -55,30 +55,32 @@ public class ${entity} implements Serializable {
 #if(${field.keyFlag})
 #if(${field.keyFlag})
 ## 主键
 ## 主键
 #if(${field.keyIdentityFlag})
 #if(${field.keyIdentityFlag})
-	@TableId(value="${field.name}", type= IdType.AUTO)
+    @TableId(value = "${field.name}", type = IdType.AUTO)
+#elseif(!$null.isNull(${idType}) && "$!idType" != "")
+    @TableId(value = "${field.name}", type = IdType.${idType})
 #elseif(${field.convert})
 #elseif(${field.convert})
-	@TableId("${field.name}")
+    @TableId("${field.name}")
 #end
 #end
 ## 普通字段
 ## 普通字段
 #elseif(${field.fill})
 #elseif(${field.fill})
 ## -----   存在字段填充设置   -----
 ## -----   存在字段填充设置   -----
 #if(${field.convert})
 #if(${field.convert})
-	@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
+    @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
 #else
 #else
-	@TableField(fill = FieldFill.${field.fill})
+    @TableField(fill = FieldFill.${field.fill})
 #end
 #end
 #elseif(${field.convert})
 #elseif(${field.convert})
-	@TableField("${field.name}")
+    @TableField("${field.name}")
 #end
 #end
 ## 乐观锁注解
 ## 乐观锁注解
 #if(${versionFieldName}==${field.name})
 #if(${versionFieldName}==${field.name})
-	@Version
+    @Version
 #end
 #end
 ## 逻辑删除注解
 ## 逻辑删除注解
 #if(${logicDeleteFieldName}==${field.name})
 #if(${logicDeleteFieldName}==${field.name})
-	@TableLogic
+    @TableLogic
 #end
 #end
-	private ${field.propertyType} ${field.propertyName};
+    private ${field.propertyType} ${field.propertyName};
 #end
 #end
 ## ----------  END 字段循环遍历  ----------
 ## ----------  END 字段循环遍历  ----------
 
 
@@ -90,52 +92,52 @@ public class ${entity} implements Serializable {
 #set($getprefix="get")
 #set($getprefix="get")
 #end
 #end
 
 
-	public ${field.propertyType} ${getprefix}${field.capitalName}() {
-		return ${field.propertyName};
-	}
+    public ${field.propertyType} ${getprefix}${field.capitalName}() {
+        return ${field.propertyName};
+    }
 
 
 #if(${entityBuilderModel})
 #if(${entityBuilderModel})
-	public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
+    public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
 #else
 #else
-	public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
+    public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
 #end
 #end
-		this.${field.propertyName} = ${field.propertyName};
+        this.${field.propertyName} = ${field.propertyName};
 #if(${entityBuilderModel})
 #if(${entityBuilderModel})
-		return this;
+        return this;
 #end
 #end
-	}
+    }
 #end
 #end
 #end
 #end
 
 
 #if(${entityColumnConstant})
 #if(${entityColumnConstant})
 #foreach($field in ${table.fields})
 #foreach($field in ${table.fields})
-	public static final String ${field.name.toUpperCase()} = "${field.name}";
+    public static final String ${field.name.toUpperCase()} = "${field.name}";
 
 
 #end
 #end
 #end
 #end
 #if(${activeRecord})
 #if(${activeRecord})
-	@Override
-	protected Serializable pkVal() {
+    @Override
+    protected Serializable pkVal() {
 #if(${keyPropertyName})
 #if(${keyPropertyName})
-		return this.${keyPropertyName};
+        return this.${keyPropertyName};
 #else
 #else
-		return this.id;
+        return this.id;
 #end
 #end
-	}
+    }
 
 
 #end
 #end
 #if(!${entityLombokModel})
 #if(!${entityLombokModel})
-	@Override
-	public String toString() {
-		return "${entity}{" +
+    @Override
+    public String toString() {
+        return "${entity}{" +
 #foreach($field in ${table.fields})
 #foreach($field in ${table.fields})
 #if($!{velocityCount}==1)
 #if($!{velocityCount}==1)
-		"${field.propertyName}=" + ${field.propertyName} +
+        "${field.propertyName}=" + ${field.propertyName} +
 #else
 #else
-		", ${field.propertyName}=" + ${field.propertyName} +
+        ", ${field.propertyName}=" + ${field.propertyName} +
 #end
 #end
 #end
 #end
-		"}";
-	}
+        "}";
+    }
 #end
 #end
 }
 }

+ 23 - 21
mybatis-plus-generate/src/main/resources/templates/entity.kt.vm

@@ -36,63 +36,65 @@ class ${entity} : Serializable {
 #if(${field.keyFlag})
 #if(${field.keyFlag})
 ## 主键
 ## 主键
 #if(${field.keyIdentityFlag})
 #if(${field.keyIdentityFlag})
-	@TableId(value = "${field.name}", type = IdType.AUTO)
+    @TableId(value = "${field.name}", type = IdType.AUTO)
+#elseif(!$null.isNull(${idType}) && "$!idType" != "")
+    @TableId(value = "${field.name}", type = IdType.${idType})
 #elseif(${field.convert})
 #elseif(${field.convert})
-	@TableId("${field.name}")
+    @TableId("${field.name}")
 #end
 #end
 ## 普通字段
 ## 普通字段
 #elseif(${field.fill})
 #elseif(${field.fill})
 ## -----   存在字段填充设置   -----
 ## -----   存在字段填充设置   -----
 #if(${field.convert})
 #if(${field.convert})
-	@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
+    @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
 #else
 #else
-	@TableField(fill = FieldFill.${field.fill})
+    @TableField(fill = FieldFill.${field.fill})
 #end
 #end
 #elseif(${field.convert})
 #elseif(${field.convert})
-	@TableField("${field.name}")
+    @TableField("${field.name}")
 #end
 #end
 ## 乐观锁注解
 ## 乐观锁注解
 #if(${versionFieldName}==${field.name})
 #if(${versionFieldName}==${field.name})
-	@Version
+    @Version
 #end
 #end
 ## 逻辑删除注解
 ## 逻辑删除注解
 #if(${logicDeleteFieldName}==${field.name})
 #if(${logicDeleteFieldName}==${field.name})
-	@TableLogic
+    @TableLogic
 #end
 #end
-	var ${field.propertyName}: ${field.propertyType}? = null
+    var ${field.propertyName}: ${field.propertyType}? = null
 #end
 #end
 ## ----------  END 字段循环遍历  ----------
 ## ----------  END 字段循环遍历  ----------
 
 
 
 
 #if(${entityColumnConstant})
 #if(${entityColumnConstant})
-	companion object {
+    companion object {
 #foreach($field in ${table.fields})
 #foreach($field in ${table.fields})
 
 
-		const val ${field.name.toUpperCase()} : String = "${field.name}"
+        const val ${field.name.toUpperCase()} : String = "${field.name}"
 
 
 #end
 #end
-	}
+    }
 
 
 #end
 #end
 #if(${activeRecord})
 #if(${activeRecord})
-	override fun pkVal(): Serializable {
+    override fun pkVal(): Serializable {
 #if(${keyPropertyName})
 #if(${keyPropertyName})
-		return ${keyPropertyName}!!
+        return ${keyPropertyName}!!
 #else
 #else
-		return id!!
+        return id!!
 #end
 #end
-	}
+    }
 
 
 #end
 #end
-	override fun toString(): String {
-		return "${entity}{" +
+    override fun toString(): String {
+        return "${entity}{" +
 #foreach($field in ${table.fields})
 #foreach($field in ${table.fields})
 #if($!{velocityCount}==1)
 #if($!{velocityCount}==1)
-		"${field.propertyName}=" + ${field.propertyName} +
+        "${field.propertyName}=" + ${field.propertyName} +
 #else
 #else
-		", ${field.propertyName}=" + ${field.propertyName} +
+        ", ${field.propertyName}=" + ${field.propertyName} +
 #end
 #end
 #end
 #end
-		"}"
-	}
+        "}"
+    }
 }
 }

+ 101 - 0
mybatis-plus-generate/src/test/java/com/baomidou/mybatisplus/test/generator/CodeGeneratorTest.java

@@ -0,0 +1,101 @@
+package com.baomidou.mybatisplus.test.generator;
+
+import org.junit.Test;
+
+import com.baomidou.mybatisplus.enums.IdType;
+import com.baomidou.mybatisplus.generator.AutoGenerator;
+import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
+import com.baomidou.mybatisplus.generator.config.GlobalConfig;
+import com.baomidou.mybatisplus.generator.config.PackageConfig;
+import com.baomidou.mybatisplus.generator.config.StrategyConfig;
+import com.baomidou.mybatisplus.generator.config.rules.DbType;
+import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
+
+/**
+ * <p>
+ *     代码生成器 示例
+ * </p>
+ *
+ * @author K神
+ * @date 2017/12/29
+ */
+public class CodeGeneratorTest {
+
+	/**
+	 * 是否强制带上注解
+	 */
+	boolean enableTableFieldAnnotation = false;
+	/**
+	 * 生成的注解带上IdType类型
+	 */
+	IdType tableIdType = null;
+	/**
+	 * 是否去掉生成实体的属性名前缀
+	 */
+	String[] fieldPrefix = null;
+
+	@Test
+	public void generateCode(){
+		String packageName = "com.baomidou.springboot";
+		enableTableFieldAnnotation = false;
+		tableIdType = null;
+		generateByTables(packageName+".noannoidtype", "user");
+		enableTableFieldAnnotation = true;
+		tableIdType = null;
+		generateByTables(packageName+".noidtype", "user");
+		enableTableFieldAnnotation = false;
+		tableIdType = IdType.INPUT;
+		generateByTables(packageName+".noanno", "user");
+		enableTableFieldAnnotation = true;
+		tableIdType = IdType.INPUT;
+		generateByTables(packageName+".both", "user");
+
+		fieldPrefix = new String[]{"test"};
+		enableTableFieldAnnotation = false;
+		tableIdType = null;
+		generateByTables(packageName+".noannoidtypewithprefix", "user");
+		enableTableFieldAnnotation = true;
+		tableIdType = null;
+		generateByTables(packageName+".noidtypewithprefix", "user");
+		enableTableFieldAnnotation = false;
+		tableIdType = IdType.INPUT;
+		generateByTables(packageName+".noannowithprefix", "user");
+		enableTableFieldAnnotation = true;
+		tableIdType = IdType.INPUT;
+		generateByTables(packageName+".withannoidtypeprefix", "user");
+	}
+
+	private void generateByTables(String packageName, String... tableNames){
+		GlobalConfig config = new GlobalConfig();
+		String dbUrl = "jdbc:mysql://localhost:3306/mybatis-plus";
+		DataSourceConfig dataSourceConfig = new DataSourceConfig();
+		dataSourceConfig.setDbType(DbType.MYSQL)
+				.setUrl(dbUrl)
+				.setUsername("root")
+				.setPassword("")
+				.setDriverName("com.mysql.jdbc.Driver");
+		StrategyConfig strategyConfig = new StrategyConfig();
+		strategyConfig
+				.setCapitalMode(true)
+				.setEntityLombokModel(false)
+				.setDbColumnUnderline(true)
+				.setNaming(NamingStrategy.underline_to_camel)
+				.entityTableFieldAnnotationEnable(enableTableFieldAnnotation)
+				.fieldPrefix(fieldPrefix)//test_id -> id, test_type -> type
+				.setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
+		config.setActiveRecord(false)
+				.setIdType(tableIdType)
+				.setAuthor("K神带你飞")
+				.setOutputDir("d:\\codeGen")
+				.setFileOverride(true);
+		new AutoGenerator().setGlobalConfig(config)
+				.setDataSource(dataSourceConfig)
+				.setStrategy(strategyConfig)
+				.setPackageInfo(
+						new PackageConfig()
+								.setParent(packageName)
+								.setController("controller")
+								.setEntity("entity")
+				).execute();
+	}
+}