= преди 7 години
родител
ревизия
e1d522da31
променени са 34 файла, в които са добавени 889 реда и са изтрити 418 реда
  1. 4 4
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/AutoGenerator.java
  2. 32 32
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/ConstVal.java
  3. 39 5
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/DataSourceConfig.java
  4. 1 1
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/GlobalConfig.java
  5. 104 0
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/IDbQuery.java
  6. 8 8
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/PackageConfig.java
  7. 12 12
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/StrategyConfig.java
  8. 67 71
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/builder/ConfigBuilder.java
  9. 13 13
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/converts/MySqlTypeConvert.java
  10. 10 10
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/converts/OracleTypeConvert.java
  11. 13 13
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/converts/PostgreSqlTypeConvert.java
  12. 10 10
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/converts/SqlServerTypeConvert.java
  13. 14 0
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/po/TableField.java
  14. 6 6
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/po/TableInfo.java
  15. 44 0
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/AbstractDbQuery.java
  16. 92 0
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/MySqlQuery.java
  17. 93 0
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/OracleQuery.java
  18. 86 0
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/PostgreSqlQuery.java
  19. 108 0
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/SqlServerQuery.java
  20. 4 0
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/package-info.java
  21. 4 4
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/rules/DbColumnType.java
  22. 7 1
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/rules/DbType.java
  23. 5 5
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/rules/NamingStrategy.java
  24. 0 141
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/rules/QuerySQL.java
  25. 2 2
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/engine/FreemarkerTemplateEngine.java
  26. 3 3
      mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/engine/VelocityTemplateEngine.java
  27. 19 19
      mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/CodeGeneratorTest.java
  28. 5 5
      mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/GeneratorTest.java
  29. 22 0
      mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/MyPostgreSqlQuery.java
  30. 16 16
      mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java
  31. 18 20
      mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/PostgreSQLGenerator.java
  32. 14 14
      mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/SQLServerGenerator.java
  33. 8 2
      mybatis-plus-generator/src/test/resources/templates/dto.java.ftl
  34. 6 1
      mybatis-plus-generator/src/test/resources/templates/dto.java.vm

+ 4 - 4
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/AutoGenerator.java

@@ -83,7 +83,7 @@ public class AutoGenerator {
      * 生成代码
      */
     public void execute() {
-        logger.debug("==========================准备生成文件...==========================" );
+        logger.debug("==========================准备生成文件...==========================");
         // 初始化配置
         if (null == config) {
             config = new ConfigBuilder(packageInfo, dataSource, strategy, template, globalConfig);
@@ -97,7 +97,7 @@ public class AutoGenerator {
         }
         // 模板引擎初始化执行文件输出
         templateEngine.init(this.pretreatmentConfigBuilder(config)).mkdirs().batchOutput().open();
-        logger.debug("==========================文件生成完成!!!==========================" );
+        logger.debug("==========================文件生成完成!!!==========================");
     }
 
     /**
@@ -159,8 +159,8 @@ public class AutoGenerator {
             // Boolean类型is前缀处理
             if (config.getStrategyConfig().isEntityBooleanColumnRemoveIsPrefix()) {
                 for (TableField field : tableInfo.getFields()) {
-                    if (field.getPropertyType().equalsIgnoreCase("boolean" )) {
-                        if (field.getPropertyName().startsWith("is" )) {
+                    if (field.getPropertyType().equalsIgnoreCase("boolean")) {
+                        if (field.getPropertyName().startsWith("is")) {
                             field.setPropertyName(config.getStrategyConfig(),
                                 StringUtils.removePrefixAfterPrefixToLower(field.getPropertyName(), 2));
                         }

+ 32 - 32
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/ConstVal.java

@@ -25,48 +25,48 @@ import java.nio.charset.Charset;
  */
 public class ConstVal {
 
-    public static final String MODULENAME = "ModuleName" ;
+    public static final String MODULENAME = "ModuleName";
 
-    public static final String ENTITY = "Entity" ;
-    public static final String SERIVCE = "Service" ;
-    public static final String SERVICEIMPL = "ServiceImpl" ;
-    public static final String MAPPER = "Mapper" ;
-    public static final String XML = "Xml" ;
-    public static final String CONTROLLER = "Controller" ;
+    public static final String ENTITY = "Entity";
+    public static final String SERIVCE = "Service";
+    public static final String SERVICEIMPL = "ServiceImpl";
+    public static final String MAPPER = "Mapper";
+    public static final String XML = "Xml";
+    public static final String CONTROLLER = "Controller";
 
-    public static final String ENTITY_PATH = "entity_path" ;
-    public static final String SERIVCE_PATH = "serivce_path" ;
-    public static final String SERVICEIMPL_PATH = "serviceimpl_path" ;
-    public static final String MAPPER_PATH = "mapper_path" ;
-    public static final String XML_PATH = "xml_path" ;
-    public static final String CONTROLLER_PATH = "controller_path" ;
+    public static final String ENTITY_PATH = "entity_path";
+    public static final String SERIVCE_PATH = "serivce_path";
+    public static final String SERVICEIMPL_PATH = "serviceimpl_path";
+    public static final String MAPPER_PATH = "mapper_path";
+    public static final String XML_PATH = "xml_path";
+    public static final String CONTROLLER_PATH = "controller_path";
 
-    public static final String JAVA_TMPDIR = "java.io.tmpdir" ;
-    public static final String UTF8 = Charset.forName("UTF-8" ).name();
-    public static final String UNDERLINE = "_" ;
+    public static final String JAVA_TMPDIR = "java.io.tmpdir";
+    public static final String UTF8 = Charset.forName("UTF-8").name();
+    public static final String UNDERLINE = "_";
 
-    public static final String JAVA_SUFFIX = ".java" ;
-    public static final String KT_SUFFIX = ".kt" ;
-    public static final String XML_SUFFIX = ".xml" ;
+    public static final String JAVA_SUFFIX = ".java";
+    public static final String KT_SUFFIX = ".kt";
+    public static final String XML_SUFFIX = ".xml";
 
-    public static final String TEMPLATE_ENTITY_JAVA = "/templates/entity.java" ;
-    public static final String TEMPLATE_ENTITY_KT = "/templates/entity.kt" ;
-    public static final String TEMPLATE_MAPPER = "/templates/mapper.java" ;
-    public static final String TEMPLATE_XML = "/templates/mapper.xml" ;
-    public static final String TEMPLATE_SERVICE = "/templates/service.java" ;
-    public static final String TEMPLATE_SERVICEIMPL = "/templates/serviceImpl.java" ;
-    public static final String TEMPLATE_CONTROLLER = "/templates/controller.java" ;
+    public static final String TEMPLATE_ENTITY_JAVA = "/templates/entity.java";
+    public static final String TEMPLATE_ENTITY_KT = "/templates/entity.kt";
+    public static final String TEMPLATE_MAPPER = "/templates/mapper.java";
+    public static final String TEMPLATE_XML = "/templates/mapper.xml";
+    public static final String TEMPLATE_SERVICE = "/templates/service.java";
+    public static final String TEMPLATE_SERVICEIMPL = "/templates/serviceImpl.java";
+    public static final String TEMPLATE_CONTROLLER = "/templates/controller.java";
 
-    public static final String VM_LOADPATH_KEY = "file.resource.loader.class" ;
-    public static final String VM_LOADPATH_VALUE = "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader" ;
+    public static final String VM_LOADPATH_KEY = "file.resource.loader.class";
+    public static final String VM_LOADPATH_VALUE = "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader";
 
-    public static final String SUPERD_MAPPER_CLASS = "com.baomidou.mybatisplus.mapper.BaseMapper" ;
-    public static final String SUPERD_SERVICE_CLASS = "com.baomidou.mybatisplus.service.IService" ;
-    public static final String SUPERD_SERVICEIMPL_CLASS = "com.baomidou.mybatisplus.service.impl.ServiceImpl" ;
+    public static final String SUPERD_MAPPER_CLASS = "com.baomidou.mybatisplus.mapper.BaseMapper";
+    public static final String SUPERD_SERVICE_CLASS = "com.baomidou.mybatisplus.service.IService";
+    public static final String SUPERD_SERVICEIMPL_CLASS = "com.baomidou.mybatisplus.service.impl.ServiceImpl";
 
     /**
      * 输出相关常量
      */
-    public static final String OUT_CONFIG = "config" ;
+    public static final String OUT_CONFIG = "config";
 
 }

+ 39 - 5
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/DataSourceConfig.java

@@ -24,6 +24,10 @@ import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
 import com.baomidou.mybatisplus.generator.config.converts.OracleTypeConvert;
 import com.baomidou.mybatisplus.generator.config.converts.PostgreSqlTypeConvert;
 import com.baomidou.mybatisplus.generator.config.converts.SqlServerTypeConvert;
+import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
+import com.baomidou.mybatisplus.generator.config.querys.OracleQuery;
+import com.baomidou.mybatisplus.generator.config.querys.PostgreSqlQuery;
+import com.baomidou.mybatisplus.generator.config.querys.SqlServerQuery;
 import com.baomidou.mybatisplus.generator.config.rules.DbType;
 
 /**
@@ -36,6 +40,10 @@ import com.baomidou.mybatisplus.generator.config.rules.DbType;
  */
 public class DataSourceConfig {
 
+    /**
+     * 数据库信息查询
+     */
+    private IDbQuery dbQuery;
     /**
      * 数据库类型
      */
@@ -43,7 +51,7 @@ public class DataSourceConfig {
     /**
      * PostgreSQL schemaname
      */
-    private String schemaname = "public" ;
+    private String schemaname = "public";
     /**
      * 类型转换
      */
@@ -65,6 +73,32 @@ public class DataSourceConfig {
      */
     private String password;
 
+    public IDbQuery getDbQuery() {
+        if (null == dbQuery) {
+            switch (getDbType()) {
+                case ORACLE:
+                    dbQuery = new OracleQuery();
+                    break;
+                case SQL_SERVER:
+                    dbQuery = new SqlServerQuery();
+                    break;
+                case POSTGRE_SQL:
+                    dbQuery = new PostgreSqlQuery();
+                    break;
+                default:
+                    // 默认 MYSQL
+                    dbQuery = new MySqlQuery();
+                    break;
+            }
+        }
+        return dbQuery;
+    }
+
+    public DataSourceConfig setDbQuery(IDbQuery dbQuery) {
+        this.dbQuery = dbQuery;
+        return this;
+    }
+
     /**
      * 判断数据库类型
      *
@@ -72,14 +106,14 @@ public class DataSourceConfig {
      */
     public DbType getDbType() {
         if (null == dbType) {
-            if (driverName.contains("mysql" )) {
+            if (driverName.contains("mysql")) {
                 dbType = DbType.MYSQL;
-            } else if (driverName.contains("oracle" )) {
+            } else if (driverName.contains("oracle")) {
                 dbType = DbType.ORACLE;
-            } else if (driverName.contains("postgresql" )) {
+            } else if (driverName.contains("postgresql")) {
                 dbType = DbType.POSTGRE_SQL;
             } else {
-                throw new MybatisPlusException("Unknown type of database!" );
+                throw new MybatisPlusException("Unknown type of database!");
             }
         }
         return dbType;

+ 1 - 1
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/GlobalConfig.java

@@ -30,7 +30,7 @@ public class GlobalConfig {
     /**
      * 生成文件的输出目录【默认 D 盘根目录】
      */
-    private String outputDir = "D://" ;
+    private String outputDir = "D://";
 
     /**
      * 是否覆盖已有文件

+ 104 - 0
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/IDbQuery.java

@@ -0,0 +1,104 @@
+/*
+ * 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.config;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import com.baomidou.mybatisplus.generator.config.rules.DbType;
+
+/**
+ * <p>
+ * 表数据查询接口
+ * </p>
+ *
+ * @author hubin
+ * @since 2018-01-16
+ */
+public interface IDbQuery {
+
+
+    /**
+     * 数据库类型
+     */
+    DbType dbType();
+
+
+    /**
+     * 表信息查询 SQL
+     */
+    String tablesSql();
+
+
+    /**
+     * 表字段信息查询 SQL
+     */
+    String tableFieldsSql();
+
+
+    /**
+     * 表名称
+     */
+    String tableName();
+
+
+    /**
+     * 表注释
+     */
+    String tableComment();
+
+
+    /**
+     * 字段名称
+     */
+    String fieldName();
+
+
+    /**
+     * 字段类型
+     */
+    String fieldType();
+
+
+    /**
+     * 字段注释
+     */
+    String fieldComment();
+
+
+    /**
+     * 主键字段
+     */
+    String fieldKey();
+
+
+    /**
+     * <p>
+     * 判断主键是否为identity,目前仅对mysql进行检查
+     * </p>
+     *
+     * @param results ResultSet
+     * @return 主键是否为identity
+     * @throws SQLException
+     */
+    boolean isKeyIdentity(ResultSet results) throws SQLException;
+
+
+    /**
+     * 自定义字段名称
+     */
+    String[] fieldCustom();
+}

+ 8 - 8
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/PackageConfig.java

@@ -30,7 +30,7 @@ public class PackageConfig {
     /**
      * 父包名。如果为空,将下面子包名必须写全部, 否则就只需写子包名
      */
-    private String parent = "com.baomidou" ;
+    private String parent = "com.baomidou";
 
     /**
      * 父包模块名。
@@ -40,31 +40,31 @@ public class PackageConfig {
     /**
      * Entity包名
      */
-    private String entity = "entity" ;
+    private String entity = "entity";
 
     /**
      * Service包名
      */
-    private String service = "service" ;
+    private String service = "service";
 
     /**
      * Service Impl包名
      */
-    private String serviceImpl = "service.impl" ;
+    private String serviceImpl = "service.impl";
     /**
      * Mapper包名
      */
-    private String mapper = "mapper" ;
+    private String mapper = "mapper";
 
     /**
      * Mapper XML包名
      */
-    private String xml = "mapper.xml" ;
+    private String xml = "mapper.xml";
 
     /**
      * Controller包名
      */
-    private String controller = "web" ;
+    private String controller = "web";
 
     public String getParent() {
         if (StringUtils.isNotEmpty(moduleName)) {
@@ -134,7 +134,7 @@ public class PackageConfig {
 
     public String getController() {
         if (StringUtils.isEmpty(controller)) {
-            return "web" ;
+            return "web";
         }
         return controller;
     }

+ 12 - 12
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/StrategyConfig.java

@@ -96,7 +96,7 @@ public class StrategyConfig {
      */
     private String superControllerClass;
 
-    /*
+    /**
      * 需要包含的表名(与exclude二选一配置)
      */
     private String[] include = null;
@@ -181,16 +181,6 @@ public class StrategyConfig {
         return isCapitalMode && StringUtils.isCapitalMode(word);
     }
 
-
-    public boolean isSkipView() {
-        return skipView;
-    }
-
-    public StrategyConfig setSkipView(boolean skipView) {
-        this.skipView = skipView;
-        return this;
-    }
-
     /**
      * <p>
      * 表名称包含指定前缀
@@ -222,6 +212,15 @@ public class StrategyConfig {
         return this;
     }
 
+    public boolean isSkipView() {
+        return skipView;
+    }
+
+    public StrategyConfig setSkipView(boolean skipView) {
+        this.skipView = skipView;
+        return this;
+    }
+
     public NamingStrategy getNaming() {
         return naming;
     }
@@ -433,8 +432,9 @@ public class StrategyConfig {
         return fieldPrefix;
     }
 
-    public void setFieldPrefix(String[] fieldPrefix) {
+    public StrategyConfig setFieldPrefix(String[] fieldPrefix) {
         this.fieldPrefix = fieldPrefix;
+        return this;
     }
 
     public StrategyConfig fieldPrefix(String... fieldPrefixs) {

+ 67 - 71
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/builder/ConfigBuilder.java

@@ -32,6 +32,7 @@ import com.baomidou.mybatisplus.generator.InjectionConfig;
 import com.baomidou.mybatisplus.generator.config.ConstVal;
 import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
 import com.baomidou.mybatisplus.generator.config.GlobalConfig;
+import com.baomidou.mybatisplus.generator.config.IDbQuery;
 import com.baomidou.mybatisplus.generator.config.PackageConfig;
 import com.baomidou.mybatisplus.generator.config.StrategyConfig;
 import com.baomidou.mybatisplus.generator.config.TemplateConfig;
@@ -40,7 +41,6 @@ import com.baomidou.mybatisplus.generator.config.po.TableFill;
 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 import com.baomidou.mybatisplus.generator.config.rules.DbType;
 import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
-import com.baomidou.mybatisplus.generator.config.rules.QuerySQL;
 
 /**
  * <p>
@@ -67,7 +67,7 @@ public class ConfigBuilder {
     /**
      * SQL语句类型
      */
-    private QuerySQL querySQL;
+    private IDbQuery dbQuery;
     private String superEntityClass;
     private String superMapperClass;
     /**
@@ -101,6 +101,7 @@ public class ConfigBuilder {
      */
     private InjectionConfig injectionConfig;
 
+
     /**
      * <p>
      * 在构造器中处理配置
@@ -156,6 +157,7 @@ public class ConfigBuilder {
         return packageInfo;
     }
 
+
     /**
      * <p>
      * 所有路径配置
@@ -167,14 +169,17 @@ public class ConfigBuilder {
         return pathInfo;
     }
 
+
     public String getSuperEntityClass() {
         return superEntityClass;
     }
 
+
     public String getSuperMapperClass() {
         return superMapperClass;
     }
 
+
     /**
      * <p>
      * 获取超类定义
@@ -186,14 +191,17 @@ public class ConfigBuilder {
         return superServiceClass;
     }
 
+
     public String getSuperServiceImplClass() {
         return superServiceImplClass;
     }
 
+
     public String getSuperControllerClass() {
         return superControllerClass;
     }
 
+
     /**
      * <p>
      * 表信息
@@ -210,6 +218,7 @@ public class ConfigBuilder {
         return this;
     }
 
+
     /**
      * <p>
      * 模板路径配置信息
@@ -233,7 +242,7 @@ public class ConfigBuilder {
      * @param config    PackageConfig
      */
     private void handlerPackage(TemplateConfig template, String outputDir, PackageConfig config) {
-        packageInfo = new HashMap<>();
+        packageInfo = new HashMap<>(8);
         packageInfo.put(ConstVal.MODULENAME, config.getModuleName());
         packageInfo.put(ConstVal.ENTITY, joinPackage(config.getParent(), config.getEntity()));
         packageInfo.put(ConstVal.MAPPER, joinPackage(config.getParent(), config.getMapper()));
@@ -243,7 +252,7 @@ public class ConfigBuilder {
         packageInfo.put(ConstVal.CONTROLLER, joinPackage(config.getParent(), config.getController()));
 
         // 生成路径信息
-        pathInfo = new HashMap<>();
+        pathInfo = new HashMap<>(6);
         if (StringUtils.isNotEmpty(template.getEntity(getGlobalConfig().isKotlin()))) {
             pathInfo.put(ConstVal.ENTITY_PATH, joinPath(outputDir, packageInfo.get(ConstVal.ENTITY)));
         }
@@ -264,6 +273,7 @@ public class ConfigBuilder {
         }
     }
 
+
     /**
      * <p>
      * 处理数据源配置
@@ -273,9 +283,10 @@ public class ConfigBuilder {
      */
     private void handlerDataSource(DataSourceConfig config) {
         connection = config.getConn();
-        querySQL = getQuerySQL(config.getDbType());
+        dbQuery = config.getDbQuery();
     }
 
+
     /**
      * <p>
      * 处理数据库表 加载数据库表、列、注释相关数据集
@@ -288,6 +299,7 @@ public class ConfigBuilder {
         tableInfoList = getTablesInfo(config);
     }
 
+
     /**
      * <p>
      * 处理superClassName,IdClassType,IdStrategy配置
@@ -315,6 +327,7 @@ public class ConfigBuilder {
         superControllerClass = config.getSuperControllerClass();
     }
 
+
     /**
      * <p>
      * 处理表对应的类名称
@@ -361,6 +374,7 @@ public class ConfigBuilder {
         return tableList;
     }
 
+
     /**
      * <p>
      * 检查是否有
@@ -407,6 +421,7 @@ public class ConfigBuilder {
         }
     }
 
+
     /**
      * <p>
      * 获取所有的数据库表信息
@@ -416,7 +431,7 @@ public class ConfigBuilder {
         boolean isInclude = (null != config.getInclude() && config.getInclude().length > 0);
         boolean isExclude = (null != config.getExclude() && config.getExclude().length > 0);
         if (isInclude && isExclude) {
-            throw new RuntimeException("<strategy> 标签中 <include> 与 <exclude> 只能配置一项!" );
+            throw new RuntimeException("<strategy> 标签中 <include> 与 <exclude> 只能配置一项!");
         }
         //所有的表信息
         List<TableInfo> tableList = new ArrayList<>();
@@ -429,37 +444,37 @@ public class ConfigBuilder {
         Set<String> notExistTables = new HashSet<>();
         PreparedStatement preparedStatement = null;
         try {
-            String tableCommentsSql = querySQL.getTableCommentsSql();
-            if (QuerySQL.POSTGRE_SQL == querySQL) {
-                tableCommentsSql = String.format(tableCommentsSql, dataSourceConfig.getSchemaname());
+            String tablesSql = dbQuery.tablesSql();
+            if (DbType.POSTGRE_SQL == dbQuery.dbType()) {
+                tablesSql = String.format(tablesSql, dataSourceConfig.getSchemaname());
             }
             //oracle数据库表太多,出现最大游标错误
-            else if (QuerySQL.ORACLE == querySQL) {
+            else if (DbType.ORACLE == dbQuery.dbType()) {
                 if (isInclude) {
-                    StringBuilder sb = new StringBuilder(tableCommentsSql);
-                    sb.append(" WHERE " ).append(querySQL.getTableName()).append(" IN (" );
+                    StringBuilder sb = new StringBuilder(tablesSql);
+                    sb.append(" WHERE ").append(dbQuery.tableName()).append(" IN (");
                     for (String tbname : config.getInclude()) {
-                        sb.append("'" ).append(tbname.toUpperCase()).append("'," );
+                        sb.append("'").append(tbname.toUpperCase()).append("',");
                     }
-                    sb.replace(sb.length() - 1, sb.length(), ")" );
-                    tableCommentsSql = sb.toString();
+                    sb.replace(sb.length() - 1, sb.length(), ")");
+                    tablesSql = sb.toString();
                 } else if (isExclude) {
-                    StringBuilder sb = new StringBuilder(tableCommentsSql);
-                    sb.append(" WHERE " ).append(querySQL.getTableName()).append(" NOT IN (" );
+                    StringBuilder sb = new StringBuilder(tablesSql);
+                    sb.append(" WHERE ").append(dbQuery.tableName()).append(" NOT IN (");
                     for (String tbname : config.getExclude()) {
-                        sb.append("'" ).append(tbname.toUpperCase()).append("'," );
+                        sb.append("'").append(tbname.toUpperCase()).append("',");
                     }
-                    sb.replace(sb.length() - 1, sb.length(), ")" );
-                    tableCommentsSql = sb.toString();
+                    sb.replace(sb.length() - 1, sb.length(), ")");
+                    tablesSql = sb.toString();
                 }
             }
-            preparedStatement = connection.prepareStatement(tableCommentsSql);
+            preparedStatement = connection.prepareStatement(tablesSql);
             ResultSet results = preparedStatement.executeQuery();
             TableInfo tableInfo;
             while (results.next()) {
-                String tableName = results.getString(querySQL.getTableName());
+                String tableName = results.getString(dbQuery.tableName());
                 if (StringUtils.isNotEmpty(tableName)) {
-                    String tableComment = results.getString(querySQL.getTableComment());
+                    String tableComment = results.getString(dbQuery.tableComment());
                     if (config.isSkipView() && "VIEW".equals(tableComment)) {
                         // 跳过视图
                         continue;
@@ -486,7 +501,7 @@ public class ConfigBuilder {
                     }
                     tableList.add(tableInfo);
                 } else {
-                    System.err.println("当前数据库为空!!!" );
+                    System.err.println("当前数据库为空!!!");
                 }
             }
             // 将已经存在的表移除,获取配置中数据库不存在的表
@@ -495,7 +510,7 @@ public class ConfigBuilder {
             }
 
             if (notExistTables.size() > 0) {
-                System.err.println("表 " + notExistTables + " 在数据库中不存在!!!" );
+                System.err.println("表 " + notExistTables + " 在数据库中不存在!!!");
             }
 
             // 需要反向生成的表信息
@@ -531,28 +546,6 @@ public class ConfigBuilder {
     }
 
 
-    /**
-     * <p>
-     * 判断主键是否为identity,目前仅对mysql进行检查
-     * </p>
-     *
-     * @param results ResultSet
-     * @return 主键是否为identity
-     * @throws SQLException
-     */
-    private boolean isKeyIdentity(ResultSet results) throws SQLException {
-        if (QuerySQL.MYSQL == this.querySQL) {
-            String extra = results.getString("Extra" );
-            if ("auto_increment".equals(extra)) {
-                return true;
-            }
-        } else if (QuerySQL.SQL_SERVER == this.querySQL) {
-            int isIdentity = results.getInt("isIdentity" );
-            return 1 == isIdentity;
-        }
-        return false;
-    }
-
     /**
      * <p>
      * 将字段信息与表信息关联
@@ -567,8 +560,8 @@ public class ConfigBuilder {
         List<TableField> fieldList = new ArrayList<>();
         List<TableField> commonFieldList = new ArrayList<>();
         try {
-            String tableFieldsSql = querySQL.getTableFieldsSql();
-            if (QuerySQL.POSTGRE_SQL == querySQL) {
+            String tableFieldsSql = dbQuery.tableFieldsSql();
+            if (DbType.POSTGRE_SQL == dbQuery.dbType()) {
                 tableFieldsSql = String.format(tableFieldsSql, dataSourceConfig.getSchemaname(), tableInfo.getName());
             } else {
                 tableFieldsSql = String.format(tableFieldsSql, tableInfo.getName());
@@ -577,25 +570,34 @@ public class ConfigBuilder {
             ResultSet results = preparedStatement.executeQuery();
             while (results.next()) {
                 TableField field = new TableField();
-                String key = results.getString(querySQL.getFieldKey());
+                String key = results.getString(dbQuery.fieldKey());
                 // 避免多重主键设置,目前只取第一个找到ID,并放到list中的索引为0的位置
-                boolean isId = StringUtils.isNotEmpty(key) && key.toUpperCase().equals("PRI" );
+                boolean isId = StringUtils.isNotEmpty(key) && key.toUpperCase().equals("PRI");
                 // 处理ID
                 if (isId && !haveId) {
                     field.setKeyFlag(true);
-                    if (isKeyIdentity(results)) {
+                    if (dbQuery.isKeyIdentity(results)) {
                         field.setKeyIdentityFlag(true);
                     }
                     haveId = true;
                 } else {
                     field.setKeyFlag(false);
                 }
+                // 自定义字段查询
+                String[] fcs = dbQuery.fieldCustom();
+                if (null != fcs) {
+                    Map<String, Object> customMap = new HashMap<>();
+                    for (String fc : fcs) {
+                        customMap.put(fc, results.getObject(fc));
+                    }
+                    field.setCustomMap(customMap);
+                }
                 // 处理其它信息
-                field.setName(results.getString(querySQL.getFieldName()));
-                field.setType(results.getString(querySQL.getFieldType()));
+                field.setName(results.getString(dbQuery.fieldName()));
+                field.setType(results.getString(dbQuery.fieldType()));
                 field.setPropertyName(strategyConfig, processName(field.getName(), strategy));
                 field.setColumnType(dataSourceConfig.getTypeConvert().processTypeConvert(field.getType()));
-                field.setComment(results.getString(querySQL.getFieldComment()));
+                field.setComment(results.getString(dbQuery.fieldComment()));
                 if (strategyConfig.includeSuperEntityColumns(field.getName())) {
                     // 跳过公共字段
                     commonFieldList.add(field);
@@ -621,6 +623,7 @@ public class ConfigBuilder {
         return tableInfo;
     }
 
+
     /**
      * <p>
      * 连接路径字符串
@@ -637,10 +640,11 @@ public class ConfigBuilder {
         if (!StringUtils.endsWith(parentDir, File.separator)) {
             parentDir += File.separator;
         }
-        packageName = packageName.replaceAll("\\." , "\\" + File.separator);
+        packageName = packageName.replaceAll("\\.", "\\" + File.separator);
         return parentDir + packageName;
     }
 
+
     /**
      * <p>
      * 连接父子包名
@@ -657,6 +661,7 @@ public class ConfigBuilder {
         return parent + "." + subPackage;
     }
 
+
     /**
      * <p>
      * 处理字段名称
@@ -668,6 +673,7 @@ public class ConfigBuilder {
         return processName(name, strategy, this.strategyConfig.getFieldPrefix());
     }
 
+
     /**
      * <p>
      * 处理表/字段名称
@@ -702,44 +708,34 @@ public class ConfigBuilder {
         return propertyName;
     }
 
-    /**
-     * <p>
-     * 获取当前的SQL类型
-     * </p>
-     *
-     * @return DB类型
-     */
-    private QuerySQL getQuerySQL(DbType dbType) {
-        for (QuerySQL qs : QuerySQL.values()) {
-            if (qs.getDbType().equals(dbType.getValue())) {
-                return qs;
-            }
-        }
-        return QuerySQL.MYSQL;
-    }
 
     public StrategyConfig getStrategyConfig() {
         return strategyConfig;
     }
 
+
     public ConfigBuilder setStrategyConfig(StrategyConfig strategyConfig) {
         this.strategyConfig = strategyConfig;
         return this;
     }
 
+
     public GlobalConfig getGlobalConfig() {
         return globalConfig;
     }
 
+
     public ConfigBuilder setGlobalConfig(GlobalConfig globalConfig) {
         this.globalConfig = globalConfig;
         return this;
     }
 
+
     public InjectionConfig getInjectionConfig() {
         return injectionConfig;
     }
 
+
     public ConfigBuilder setInjectionConfig(InjectionConfig injectionConfig) {
         this.injectionConfig = injectionConfig;
         return this;

+ 13 - 13
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/converts/MySqlTypeConvert.java

@@ -31,31 +31,31 @@ public class MySqlTypeConvert implements ITypeConvert {
     @Override
     public DbColumnType processTypeConvert(String fieldType) {
         String t = fieldType.toLowerCase();
-        if (t.contains("char" ) || t.contains("text" )) {
+        if (t.contains("char") || t.contains("text")) {
             return DbColumnType.STRING;
-        } else if (t.contains("bigint" )) {
+        } else if (t.contains("bigint")) {
             return DbColumnType.LONG;
-        } else if (t.contains("int" )) {
+        } else if (t.contains("int")) {
             return DbColumnType.INTEGER;
-        } else if (t.contains("date" ) || t.contains("time" ) || t.contains("year" )) {
+        } else if (t.contains("date") || t.contains("time") || t.contains("year")) {
             return DbColumnType.DATE;
-        } else if (t.contains("text" )) {
+        } else if (t.contains("text")) {
             return DbColumnType.STRING;
-        } else if (t.contains("bit" )) {
+        } else if (t.contains("bit")) {
             return DbColumnType.BOOLEAN;
-        } else if (t.contains("decimal" )) {
+        } else if (t.contains("decimal")) {
             return DbColumnType.BIG_DECIMAL;
-        } else if (t.contains("clob" )) {
+        } else if (t.contains("clob")) {
             return DbColumnType.CLOB;
-        } else if (t.contains("blob" )) {
+        } else if (t.contains("blob")) {
             return DbColumnType.BLOB;
-        } else if (t.contains("binary" )) {
+        } else if (t.contains("binary")) {
             return DbColumnType.BYTE_ARRAY;
-        } else if (t.contains("float" )) {
+        } else if (t.contains("float")) {
             return DbColumnType.FLOAT;
-        } else if (t.contains("double" )) {
+        } else if (t.contains("double")) {
             return DbColumnType.DOUBLE;
-        } else if (t.contains("json" ) || t.contains("enum" )) {
+        } else if (t.contains("json") || t.contains("enum")) {
             return DbColumnType.STRING;
         }
         return DbColumnType.STRING;

+ 10 - 10
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/converts/OracleTypeConvert.java

@@ -31,26 +31,26 @@ public class OracleTypeConvert implements ITypeConvert {
     @Override
     public DbColumnType processTypeConvert(String fieldType) {
         String t = fieldType.toUpperCase();
-        if (t.contains("CHAR" )) {
+        if (t.contains("CHAR")) {
             return DbColumnType.STRING;
-        } else if (t.contains("DATE" ) || t.contains("TIMESTAMP" )) {
+        } else if (t.contains("DATE") || t.contains("TIMESTAMP")) {
             return DbColumnType.DATE;
-        } else if (t.contains("NUMBER" )) {
-            if (t.matches("NUMBER\\(+\\d\\)" )) {
+        } else if (t.contains("NUMBER")) {
+            if (t.matches("NUMBER\\(+\\d\\)")) {
                 return DbColumnType.INTEGER;
-            } else if (t.matches("NUMBER\\(+\\d{2}+\\)" )) {
+            } else if (t.matches("NUMBER\\(+\\d{2}+\\)")) {
                 return DbColumnType.LONG;
             }
             return DbColumnType.DOUBLE;
-        } else if (t.contains("FLOAT" )) {
+        } else if (t.contains("FLOAT")) {
             return DbColumnType.FLOAT;
-        } else if (t.contains("clob" )) {
+        } else if (t.contains("clob")) {
             return DbColumnType.CLOB;
-        } else if (t.contains("BLOB" )) {
+        } else if (t.contains("BLOB")) {
             return DbColumnType.OBJECT;
-        } else if (t.contains("binary" )) {
+        } else if (t.contains("binary")) {
             return DbColumnType.BYTE_ARRAY;
-        } else if (t.contains("RAW" )) {
+        } else if (t.contains("RAW")) {
             return DbColumnType.BYTE_ARRAY;
         }
         return DbColumnType.STRING;

+ 13 - 13
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/converts/PostgreSqlTypeConvert.java

@@ -31,31 +31,31 @@ public class PostgreSqlTypeConvert implements ITypeConvert {
     @Override
     public DbColumnType processTypeConvert(String fieldType) {
         String t = fieldType.toLowerCase();
-        if (t.contains("char" ) || t.contains("text" )) {
+        if (t.contains("char") || t.contains("text")) {
             return DbColumnType.STRING;
-        } else if (t.contains("bigint" )) {
+        } else if (t.contains("bigint")) {
             return DbColumnType.LONG;
-        } else if (t.contains("int" )) {
+        } else if (t.contains("int")) {
             return DbColumnType.INTEGER;
-        } else if (t.contains("date" ) || t.contains("time" ) || t.contains("year" )) {
+        } else if (t.contains("date") || t.contains("time") || t.contains("year")) {
             return DbColumnType.DATE;
-        } else if (t.contains("text" )) {
+        } else if (t.contains("text")) {
             return DbColumnType.STRING;
-        } else if (t.contains("bit" )) {
+        } else if (t.contains("bit")) {
             return DbColumnType.BOOLEAN;
-        } else if (t.contains("decimal" )) {
+        } else if (t.contains("decimal")) {
             return DbColumnType.BIG_DECIMAL;
-        } else if (t.contains("clob" )) {
+        } else if (t.contains("clob")) {
             return DbColumnType.CLOB;
-        } else if (t.contains("blob" )) {
+        } else if (t.contains("blob")) {
             return DbColumnType.BYTE_ARRAY;
-        } else if (t.contains("float" )) {
+        } else if (t.contains("float")) {
             return DbColumnType.FLOAT;
-        } else if (t.contains("double" )) {
+        } else if (t.contains("double")) {
             return DbColumnType.DOUBLE;
-        } else if (t.contains("json" ) || t.contains("enum" )) {
+        } else if (t.contains("json") || t.contains("enum")) {
             return DbColumnType.STRING;
-        } else if (t.contains("boolean" )) {
+        } else if (t.contains("boolean")) {
             return DbColumnType.BOOLEAN;
         }
         return DbColumnType.STRING;

+ 10 - 10
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/converts/SqlServerTypeConvert.java

@@ -31,25 +31,25 @@ public class SqlServerTypeConvert implements ITypeConvert {
     @Override
     public DbColumnType processTypeConvert(String fieldType) {
         String t = fieldType.toLowerCase();
-        if (t.contains("char" ) || t.contains("text" ) || t.contains("xml" )) {
+        if (t.contains("char") || t.contains("text") || t.contains("xml")) {
             return DbColumnType.STRING;
-        } else if (t.contains("bigint" )) {
+        } else if (t.contains("bigint")) {
             return DbColumnType.LONG;
-        } else if (t.contains("int" )) {
+        } else if (t.contains("int")) {
             return DbColumnType.INTEGER;
-        } else if (t.contains("date" ) || t.contains("time" )) {
+        } else if (t.contains("date") || t.contains("time")) {
             return DbColumnType.DATE;
-        } else if (t.contains("text" )) {
+        } else if (t.contains("text")) {
             return DbColumnType.STRING;
-        } else if (t.contains("bit" )) {
+        } else if (t.contains("bit")) {
             return DbColumnType.BOOLEAN;
-        } else if (t.contains("decimal" ) || t.contains("numeric" )) {
+        } else if (t.contains("decimal") || t.contains("numeric")) {
             return DbColumnType.DOUBLE;
-        } else if (t.contains("money" )) {
+        } else if (t.contains("money")) {
             return DbColumnType.BIG_DECIMAL;
-        } else if (t.contains("binary" ) || t.contains("image" )) {
+        } else if (t.contains("binary") || t.contains("image")) {
             return DbColumnType.BYTE_ARRAY;
-        } else if (t.contains("float" ) || t.contains("real" )) {
+        } else if (t.contains("float") || t.contains("real")) {
             return DbColumnType.FLOAT;
         }
         return DbColumnType.STRING;

+ 14 - 0
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/po/TableField.java

@@ -15,6 +15,8 @@
  */
 package com.baomidou.mybatisplus.generator.config.po;
 
+import java.util.Map;
+
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.generator.config.StrategyConfig;
 import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
@@ -41,6 +43,10 @@ public class TableField {
     private DbColumnType columnType;
     private String comment;
     private String fill;
+    /**
+     * 自定义查询字段列表
+     */
+    private Map<String, Object> customMap;
 
     public boolean isConvert() {
         return convert;
@@ -157,4 +163,12 @@ public class TableField {
     public void setFill(String fill) {
         this.fill = fill;
     }
+
+    public Map<String, Object> getCustomMap() {
+        return customMap;
+    }
+
+    public void setCustomMap(Map<String, Object> customMap) {
+        this.customMap = customMap;
+    }
 }

+ 6 - 6
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/po/TableInfo.java

@@ -168,20 +168,20 @@ public class TableInfo {
                 if (field.isKeyFlag()) {
                     // 主键
                     if (field.isConvert() || field.isKeyIdentityFlag()) {
-                        pkgSet.add("com.baomidou.mybatisplus.annotation.TableId" );
+                        pkgSet.add("com.baomidou.mybatisplus.annotations.TableId");
                     }
                     // 自增
                     if (field.isKeyIdentityFlag()) {
-                        pkgSet.add("com.baomidou.mybatisplus.enums.IdType" );
+                        pkgSet.add("com.baomidou.mybatisplus.enums.IdType");
                     }
                 } else if (field.isConvert()) {
                     // 普通字段
-                    pkgSet.add("com.baomidou.mybatisplus.annotation.TableField" );
+                    pkgSet.add("com.baomidou.mybatisplus.annotations.TableField");
                 }
                 if (null != field.getFill()) {
                     // 填充字段
-                    pkgSet.add("com.baomidou.mybatisplus.annotation.TableField" );
-                    pkgSet.add("com.baomidou.mybatisplus.enums.FieldFill" );
+                    pkgSet.add("com.baomidou.mybatisplus.annotations.TableField");
+                    pkgSet.add("com.baomidou.mybatisplus.enums.FieldFill");
                 }
             }
             if (!pkgSet.isEmpty()) {
@@ -231,7 +231,7 @@ public class TableInfo {
                 if (i == fields.size() - 1) {
                     names.append(cov2col(fd));
                 } else {
-                    names.append(cov2col(fd)).append(", " );
+                    names.append(cov2col(fd)).append(", ");
                 }
             }
             fieldNames = names.toString();

+ 44 - 0
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/AbstractDbQuery.java

@@ -0,0 +1,44 @@
+/*
+ * 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.config.querys;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import com.baomidou.mybatisplus.generator.config.IDbQuery;
+
+/**
+ * <p>
+ * 表数据查询抽象类
+ * </p>
+ *
+ * @author hubin
+ * @since 2018-01-16
+ */
+public abstract class AbstractDbQuery implements IDbQuery {
+
+
+    @Override
+    public boolean isKeyIdentity(ResultSet results) throws SQLException {
+        return false;
+    }
+
+
+    @Override
+    public String[] fieldCustom() {
+        return null;
+    }
+}

+ 92 - 0
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/MySqlQuery.java

@@ -0,0 +1,92 @@
+/*
+ * 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.config.querys;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import com.baomidou.mybatisplus.generator.config.rules.DbType;
+
+/**
+ * <p>
+ * MySql 表数据查询
+ * </p>
+ *
+ * @author hubin
+ * @since 2018-01-16
+ */
+public class MySqlQuery extends AbstractDbQuery {
+
+
+    @Override
+    public DbType dbType() {
+        return DbType.MYSQL;
+    }
+
+
+    @Override
+    public String tablesSql() {
+        return "show table status";
+    }
+
+
+    @Override
+    public String tableFieldsSql() {
+        return "show full fields from `%s`";
+    }
+
+
+    @Override
+    public String tableName() {
+        return "NAME";
+    }
+
+
+    @Override
+    public String tableComment() {
+        return "COMMENT";
+    }
+
+
+    @Override
+    public String fieldName() {
+        return "FIELD";
+    }
+
+
+    @Override
+    public String fieldType() {
+        return "TYPE";
+    }
+
+
+    @Override
+    public String fieldComment() {
+        return "COMMENT";
+    }
+
+
+    @Override
+    public String fieldKey() {
+        return "KEY";
+    }
+
+
+    @Override
+    public boolean isKeyIdentity(ResultSet results) throws SQLException {
+        return "auto_increment".equals(results.getString("Extra"));
+    }
+}

+ 93 - 0
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/OracleQuery.java

@@ -0,0 +1,93 @@
+/*
+ * 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.config.querys;
+
+import com.baomidou.mybatisplus.generator.config.rules.DbType;
+
+/**
+ * <p>
+ * Oracle 表数据查询
+ * </p>
+ *
+ * @author hubin
+ * @since 2018-01-16
+ */
+public class OracleQuery extends AbstractDbQuery {
+
+
+    @Override
+    public DbType dbType() {
+        return DbType.ORACLE;
+    }
+
+
+    @Override
+    public String tablesSql() {
+        return "SELECT * FROM USER_TAB_COMMENTS";
+    }
+
+
+    @Override
+    public String tableFieldsSql() {
+        return "SELECT A.COLUMN_NAME, CASE WHEN A.DATA_TYPE='NUMBER' THEN "
+            + "(CASE WHEN A.DATA_PRECISION IS NULL THEN A.DATA_TYPE "
+            + "WHEN NVL(A.DATA_SCALE, 0) > 0 THEN A.DATA_TYPE||'('||A.DATA_PRECISION||','||A.DATA_SCALE||')' "
+            + "ELSE A.DATA_TYPE||'('||A.DATA_PRECISION||')' END) "
+            + "ELSE A.DATA_TYPE END DATA_TYPE, B.COMMENTS,DECODE(C.POSITION, '1', 'PRI') KEY "
+            + "FROM USER_TAB_COLUMNS A INNER JOIN USER_COL_COMMENTS B ON A.TABLE_NAME = B.TABLE_NAME"
+            + " AND A.COLUMN_NAME = B.COLUMN_NAME LEFT JOIN USER_CONSTRAINTS D "
+            + "ON D.TABLE_NAME = A.TABLE_NAME AND D.CONSTRAINT_TYPE = 'P' "
+            + "LEFT JOIN USER_CONS_COLUMNS C ON C.CONSTRAINT_NAME = D.CONSTRAINT_NAME "
+            + "AND C.COLUMN_NAME=A.COLUMN_NAME WHERE A.TABLE_NAME = '%s' ORDER BY A.COLUMN_ID ";
+    }
+
+
+    @Override
+    public String tableName() {
+        return "TABLE_NAME";
+    }
+
+
+    @Override
+    public String tableComment() {
+        return "COMMENTS";
+    }
+
+
+    @Override
+    public String fieldName() {
+        return "COLUMN_NAME";
+    }
+
+
+    @Override
+    public String fieldType() {
+        return "DATA_TYPE";
+    }
+
+
+    @Override
+    public String fieldComment() {
+        return "COMMENTS";
+    }
+
+
+    @Override
+    public String fieldKey() {
+        return "KEY";
+    }
+
+}

+ 86 - 0
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/PostgreSqlQuery.java

@@ -0,0 +1,86 @@
+/*
+ * 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.config.querys;
+
+import com.baomidou.mybatisplus.generator.config.rules.DbType;
+
+/**
+ * <p>
+ * PostgreSql 表数据查询
+ * </p>
+ *
+ * @author hubin
+ * @since 2018-01-16
+ */
+public class PostgreSqlQuery extends AbstractDbQuery {
+
+
+    @Override
+    public DbType dbType() {
+        return DbType.POSTGRE_SQL;
+    }
+
+
+    @Override
+    public String tablesSql() {
+        return "SELECT A.tablename, obj_description(relfilenode, 'pg_class') AS comments FROM pg_tables A, pg_class B WHERE A.schemaname='%s' AND A.tablename = B.relname";
+    }
+
+
+    @Override
+    public String tableFieldsSql() {
+        return "SELECT A.attname AS name, format_type(A.atttypid, A.atttypmod) AS type,col_description(A.attrelid, A.attnum) AS comment, (CASE C.contype WHEN 'p' THEN 'PRI' ELSE '' END) AS key " +
+            "FROM pg_attribute A LEFT JOIN pg_constraint C ON A.attnum = C.conkey[1] AND A.attrelid = C.conrelid " +
+            "WHERE  A.attrelid = '%s.%s'::regclass AND A.attnum > 0 AND NOT A.attisdropped ORDER  BY A.attnum";
+    }
+
+
+    @Override
+    public String tableName() {
+        return "tablename";
+    }
+
+
+    @Override
+    public String tableComment() {
+        return "comments";
+    }
+
+
+    @Override
+    public String fieldName() {
+        return "name";
+    }
+
+
+    @Override
+    public String fieldType() {
+        return "type";
+    }
+
+
+    @Override
+    public String fieldComment() {
+        return "comment";
+    }
+
+
+    @Override
+    public String fieldKey() {
+        return "key";
+    }
+
+}

+ 108 - 0
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/SqlServerQuery.java

@@ -0,0 +1,108 @@
+/*
+ * 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.config.querys;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import com.baomidou.mybatisplus.generator.config.rules.DbType;
+
+/**
+ * <p>
+ * SqlServer 表数据查询
+ * </p>
+ *
+ * @author hubin
+ * @since 2018-01-16
+ */
+public class SqlServerQuery extends AbstractDbQuery {
+
+
+    @Override
+    public DbType dbType() {
+        return DbType.SQL_SERVER;
+    }
+
+
+    @Override
+    public String tablesSql() {
+        return "select cast(so.name as varchar(500)) as TABLE_NAME, " +
+            "cast(sep.value as varchar(500)) as COMMENTS from sysobjects so " +
+            "left JOIN sys.extended_properties sep on sep.major_id=so.id and sep.minor_id=0 " +
+            "where (xtype='U' or xtype='v')";
+    }
+
+
+    @Override
+    public String tableFieldsSql() {
+        return "SELECT  cast(a.NAME AS VARCHAR(500)) AS TABLE_NAME,cast(b.NAME AS VARCHAR(500)) AS COLUMN_NAME, "
+            + "cast(c.VALUE AS VARCHAR(500)) AS COMMENTS,cast(sys.types.NAME AS VARCHAR (500)) AS DATA_TYPE,"
+            + "(" + " SELECT CASE count(1) WHEN 1 then 'PRI' ELSE '' END"
+            + " FROM syscolumns,sysobjects,sysindexes,sysindexkeys,systypes "
+            + " WHERE syscolumns.xusertype = systypes.xusertype AND syscolumns.id = object_id (A.NAME) AND sysobjects.xtype = 'PK'"
+            + " AND sysobjects.parent_obj = syscolumns.id " + " AND sysindexes.id = syscolumns.id "
+            + " AND sysobjects.NAME = sysindexes.NAME AND sysindexkeys.id = syscolumns.id "
+            + " AND sysindexkeys.indid = sysindexes.indid "
+            + " AND syscolumns.colid = sysindexkeys.colid AND syscolumns.NAME = B.NAME) as 'KEY',"
+            + "  b.is_identity isIdentity "
+            + " FROM ( select name,object_id from sys.tables UNION all select name,object_id from sys.views ) a "
+            + " INNER JOIN sys.COLUMNS b ON b.object_id = a.object_id "
+            + " LEFT JOIN sys.types ON b.user_type_id = sys.types.user_type_id   "
+            + " LEFT JOIN sys.extended_properties c ON c.major_id = b.object_id AND c.minor_id = b.column_id "
+            + " WHERE a.NAME = '%s' and sys.types.NAME !='sysname' ";
+    }
+
+    @Override
+    public String tableName() {
+        return "TABLE_NAME";
+    }
+
+
+    @Override
+    public String tableComment() {
+        return "COMMENTS";
+    }
+
+
+    @Override
+    public String fieldName() {
+        return "COLUMN_NAME";
+    }
+
+
+    @Override
+    public String fieldType() {
+        return "DATA_TYPE";
+    }
+
+
+    @Override
+    public String fieldComment() {
+        return "COMMENTS";
+    }
+
+
+    @Override
+    public String fieldKey() {
+        return "KEY";
+    }
+
+
+    @Override
+    public boolean isKeyIdentity(ResultSet results) throws SQLException {
+        return 1 == results.getInt("isIdentity");
+    }
+}

+ 4 - 0
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/package-info.java

@@ -0,0 +1,4 @@
+/**
+ * 代码生成器,数据库查询相关类
+ */
+package com.baomidou.mybatisplus.generator.config.querys;

+ 4 - 4
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/rules/DbColumnType.java

@@ -46,10 +46,10 @@ public enum DbColumnType {
     CHARACTER("Character", null),
     OBJECT("Object", null),
     DATE("Date", "java.util.Date"),
-    TIME("Time", "java.sql.Time"),
-    BLOB("Blob", "java.sql.Blob"),
-    CLOB("Clob", "java.sql.Clob"),
-    TIMESTAMP("Timestamp", "java.sql.Timestamp"),
+    TIME("Time", "java.querys.Time"),
+    BLOB("Blob", "java.querys.Blob"),
+    CLOB("Clob", "java.querys.Clob"),
+    TIMESTAMP("Timestamp", "java.querys.Timestamp"),
     BIG_INTEGER("BigInteger", "java.math.BigInteger"),
     BIG_DECIMAL("BigDecimal", "java.math.BigDecimal"),
     LOCAL_DATE("LocalDate", "java.time.LocalDate"),

+ 7 - 1
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/rules/DbType.java

@@ -22,15 +22,21 @@ package com.baomidou.mybatisplus.generator.config.rules;
  * @since 2016/8/30
  */
 public enum DbType {
+    MYSQL("mysql"),
+    ORACLE("oracle"),
+    SQL_SERVER("sql_server"),
+    POSTGRE_SQL("postgre_sql"),
+    OTHER("other db");
 
-    MYSQL("mysql" ), ORACLE("oracle" ), SQL_SERVER("sql_server" ), POSTGRE_SQL("postgre_sql" );
 
     private final String value;
 
+
     DbType(String value) {
         this.value = value;
     }
 
+
     public String getValue() {
         return value;
     }

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

@@ -38,7 +38,7 @@ public enum NamingStrategy {
         // 快速检查
         if (StringUtils.isEmpty(name)) {
             // 没必要转换
-            return "" ;
+            return "";
         }
         String tempName = name;
         // 大写数字下划线组成转为小写 , 允许混合模式转为小写
@@ -74,11 +74,11 @@ public enum NamingStrategy {
      */
     public static String removePrefix(String name, String... prefix) {
         if (StringUtils.isEmpty(name)) {
-            return "" ;
+            return "";
         }
         if (null != prefix) {
             for (String pf : prefix) {
-                if (name.toLowerCase().matches("^" + pf.toLowerCase() + ".*" )) {
+                if (name.toLowerCase().matches("^" + pf.toLowerCase() + ".*")) {
                     // 判断是否有匹配的前缀,然后截取前缀
                     // 删除前缀
                     return name.substring(pf.length());
@@ -101,7 +101,7 @@ public enum NamingStrategy {
         }
         if (null != prefix) {
             for (String pf : prefix) {
-                if (name.toLowerCase().matches("^" + pf.toLowerCase() + ".*" )) {
+                if (name.toLowerCase().matches("^" + pf.toLowerCase() + ".*")) {
                     return true;
                 }
             }
@@ -130,7 +130,7 @@ public enum NamingStrategy {
         if (StringUtils.isNotEmpty(name)) {
             return name.substring(0, 1).toUpperCase() + name.substring(1);
         }
-        return "" ;
+        return "";
     }
 
 }

+ 0 - 141
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/rules/QuerySQL.java

@@ -1,141 +0,0 @@
-/*
- * 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.config.rules;
-
-/**
- * <p>
- * 表数据查询
- * </p>
- *
- * @author hubin, tangguo
- * @since 2016-04-25
- */
-public enum QuerySQL {
-    MYSQL("mysql" , "show tables" , "show table status" , "show full fields from `%s`" , "NAME" , "COMMENT" , "FIELD" , "TYPE" ,
-        "COMMENT" , "KEY" ),
-
-    ORACLE("oracle" , "SELECT * FROM USER_TABLES" , "SELECT * FROM USER_TAB_COMMENTS" ,
-        "SELECT A.COLUMN_NAME, CASE WHEN A.DATA_TYPE='NUMBER' THEN "
-            + "(CASE WHEN A.DATA_PRECISION IS NULL THEN A.DATA_TYPE "
-            + "WHEN NVL(A.DATA_SCALE, 0) > 0 THEN A.DATA_TYPE||'('||A.DATA_PRECISION||','||A.DATA_SCALE||')' "
-            + "ELSE A.DATA_TYPE||'('||A.DATA_PRECISION||')' END) "
-            + "ELSE A.DATA_TYPE END DATA_TYPE, B.COMMENTS,DECODE(C.POSITION, '1', 'PRI') KEY "
-            + "FROM USER_TAB_COLUMNS A INNER JOIN USER_COL_COMMENTS B ON A.TABLE_NAME = B.TABLE_NAME"
-            + " AND A.COLUMN_NAME = B.COLUMN_NAME LEFT JOIN USER_CONSTRAINTS D "
-            + "ON D.TABLE_NAME = A.TABLE_NAME AND D.CONSTRAINT_TYPE = 'P' "
-            + "LEFT JOIN USER_CONS_COLUMNS C ON C.CONSTRAINT_NAME = D.CONSTRAINT_NAME "
-            + "AND C.COLUMN_NAME=A.COLUMN_NAME WHERE A.TABLE_NAME = '%s' ORDER BY A.COLUMN_ID " ,
-        "TABLE_NAME" , "COMMENTS" , "COLUMN_NAME" , "DATA_TYPE" , "COMMENTS" , "KEY" ),
-
-    SQL_SERVER("sql_server" ,
-        "select cast(name as varchar(500)) as TABLE_NAME from sysObjects where (xtype='U' or xtype='v') order by name" ,
-        "select " +
-            "cast(so.name as varchar(500)) as TABLE_NAME, " +
-            "cast(sep.value as varchar(500)) as COMMENTS " +
-            "from sysobjects so " +
-            "left JOIN sys.extended_properties sep on sep.major_id=so.id and sep.minor_id=0 " +
-            "where (xtype='U' or xtype='v')" ,
-        "SELECT  cast(a.NAME AS VARCHAR(500)) AS TABLE_NAME,cast(b.NAME AS VARCHAR(500)) AS COLUMN_NAME, "
-            + "cast(c.VALUE AS VARCHAR(500)) AS COMMENTS,cast(sys.types.NAME AS VARCHAR (500)) AS DATA_TYPE,"
-            + "(" + " SELECT CASE count(1) WHEN 1 then 'PRI' ELSE '' END"
-            + " FROM syscolumns,sysobjects,sysindexes,sysindexkeys,systypes "
-            + " WHERE syscolumns.xusertype = systypes.xusertype AND syscolumns.id = object_id (A.NAME) AND sysobjects.xtype = 'PK'"
-            + " AND sysobjects.parent_obj = syscolumns.id " + " AND sysindexes.id = syscolumns.id "
-            + " AND sysobjects.NAME = sysindexes.NAME AND sysindexkeys.id = syscolumns.id "
-            + " AND sysindexkeys.indid = sysindexes.indid "
-            + " AND syscolumns.colid = sysindexkeys.colid AND syscolumns.NAME = B.NAME) as 'KEY',"
-            + "  b.is_identity isIdentity "
-            + " FROM ( select name,object_id from sys.tables UNION all select name,object_id from sys.views ) a "
-            + " INNER JOIN sys.COLUMNS b ON b.object_id = a.object_id "
-            + " LEFT JOIN sys.types ON b.user_type_id = sys.types.user_type_id   "
-            + " LEFT JOIN sys.extended_properties c ON c.major_id = b.object_id AND c.minor_id = b.column_id "
-            + " WHERE a.NAME = '%s' and sys.types.NAME !='sysname' " ,
-        "TABLE_NAME" , "COMMENTS" , "COLUMN_NAME" , "DATA_TYPE" , "COMMENTS" , "KEY" ),
-
-    POSTGRE_SQL("postgre_sql" , "select tablename from pg_tables where schemaname='%s' ORDER BY tablename" ,
-        "SELECT A.tablename, obj_description(relfilenode, 'pg_class') AS comments FROM pg_tables A, pg_class B WHERE A.schemaname='%s' AND A.tablename = B.relname" ,
-        "SELECT A.attname AS name, format_type(A.atttypid, A.atttypmod) AS type,col_description(A.attrelid, A.attnum) AS comment, (CASE C.contype WHEN 'p' THEN 'PRI' ELSE '' END) AS key " +
-            "FROM pg_attribute A LEFT JOIN pg_constraint C ON A.attnum = C.conkey[1] AND A.attrelid = C.conrelid " +
-            "WHERE  A.attrelid = '%s.%s'::regclass AND A.attnum > 0 AND NOT A.attisdropped ORDER  BY A.attnum" ,
-        "tablename" , "comments" , "name" , "type" , "comment" , "key" );
-
-    private final String dbType;
-    private final String tablesSql;
-    private final String tableCommentsSql;
-    private final String tableFieldsSql;
-    private final String tableName;
-    private final String tableComment;
-    private final String fieldName;
-    private final String fieldType;
-    private final String fieldComment;
-    private final String fieldKey;
-
-    QuerySQL(final String dbType, final String tablesSql, final String tableCommentsSql, final String tableFieldsSql,
-             final String tableName, final String tableComment, final String fieldName, final String fieldType,
-             final String fieldComment, final String fieldKey) {
-        this.dbType = dbType;
-        this.tablesSql = tablesSql;
-        this.tableCommentsSql = tableCommentsSql;
-        this.tableFieldsSql = tableFieldsSql;
-        this.tableName = tableName;
-        this.tableComment = tableComment;
-        this.fieldName = fieldName;
-        this.fieldType = fieldType;
-        this.fieldComment = fieldComment;
-        this.fieldKey = fieldKey;
-    }
-
-    public String getDbType() {
-        return dbType;
-    }
-
-    public String getTablesSql() {
-        return tablesSql;
-    }
-
-    public String getTableCommentsSql() {
-        return tableCommentsSql;
-    }
-
-    public String getTableFieldsSql() {
-        return tableFieldsSql;
-    }
-
-    public String getTableName() {
-        return tableName;
-    }
-
-    public String getTableComment() {
-        return tableComment;
-    }
-
-    public String getFieldName() {
-        return fieldName;
-    }
-
-    public String getFieldType() {
-        return fieldType;
-    }
-
-    public String getFieldComment() {
-        return fieldComment;
-    }
-
-    public String getFieldKey() {
-        return fieldKey;
-    }
-
-}

+ 2 - 2
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/engine/FreemarkerTemplateEngine.java

@@ -43,7 +43,7 @@ public class FreemarkerTemplateEngine extends AbstractTemplateEngine {
         super.init(configBuilder);
         configuration = new Configuration();
         configuration.setDefaultEncoding(ConstVal.UTF8);
-        configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, "/" );
+        configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, "/");
         return this;
     }
 
@@ -61,7 +61,7 @@ public class FreemarkerTemplateEngine extends AbstractTemplateEngine {
     @Override
     public String templateFilePath(String filePath) {
         StringBuilder fp = new StringBuilder();
-        fp.append(filePath).append(".ftl" );
+        fp.append(filePath).append(".ftl");
         return fp.toString();
     }
 }

+ 3 - 3
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/engine/VelocityTemplateEngine.java

@@ -40,7 +40,7 @@ import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
  */
 public class VelocityTemplateEngine extends AbstractTemplateEngine {
 
-    private static final String DOT_VM = ".vm" ;
+    private static final String DOT_VM = ".vm";
     private VelocityEngine velocityEngine;
 
     @Override
@@ -49,10 +49,10 @@ public class VelocityTemplateEngine extends AbstractTemplateEngine {
         if (null == velocityEngine) {
             Properties p = new Properties();
             p.setProperty(ConstVal.VM_LOADPATH_KEY, ConstVal.VM_LOADPATH_VALUE);
-            p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "" );
+            p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "");
             p.setProperty(Velocity.ENCODING_DEFAULT, ConstVal.UTF8);
             p.setProperty(Velocity.INPUT_ENCODING, ConstVal.UTF8);
-            p.setProperty("file.resource.loader.unicode" , "true" );
+            p.setProperty("file.resource.loader.unicode", "true");
             velocityEngine = new VelocityEngine(p);
         }
         return this;

+ 19 - 19
mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/CodeGeneratorTest.java

@@ -42,47 +42,47 @@ public class CodeGeneratorTest {
 
     @Test
     public void generateCode() {
-        String packageName = "com.baomidou.springboot" ;
+        String packageName = "com.baomidou.springboot";
         enableTableFieldAnnotation = false;
         tableIdType = null;
-        generateByTables(packageName + ".noannoidtype" , "user" );
+        generateByTables(packageName + ".noannoidtype", "user");
         enableTableFieldAnnotation = true;
         tableIdType = null;
-        generateByTables(packageName + ".noidtype" , "user" );
+        generateByTables(packageName + ".noidtype", "user");
         enableTableFieldAnnotation = false;
         tableIdType = IdType.INPUT;
-        generateByTables(packageName + ".noanno" , "user" );
+        generateByTables(packageName + ".noanno", "user");
         enableTableFieldAnnotation = true;
         tableIdType = IdType.INPUT;
-        generateByTables(packageName + ".both" , "user" );
+        generateByTables(packageName + ".both", "user");
 
         fieldPrefix = new String[]{"test"};
         enableTableFieldAnnotation = false;
         tableIdType = null;
-        generateByTables(packageName + ".noannoidtypewithprefix" , "user" );
+        generateByTables(packageName + ".noannoidtypewithprefix", "user");
         enableTableFieldAnnotation = true;
         tableIdType = null;
-        generateByTables(packageName + ".noidtypewithprefix" , "user" );
+        generateByTables(packageName + ".noidtypewithprefix", "user");
         enableTableFieldAnnotation = false;
         tableIdType = IdType.INPUT;
-        generateByTables(packageName + ".noannowithprefix" , "user" );
+        generateByTables(packageName + ".noannowithprefix", "user");
         enableTableFieldAnnotation = true;
         tableIdType = IdType.INPUT;
-        generateByTables(packageName + ".withannoidtypeprefix" , "user" );
+        generateByTables(packageName + ".withannoidtypeprefix", "user");
 
         serviceClassNameStartWithI = false;
-        generateByTables(packageName, "user" );
+        generateByTables(packageName, "user");
     }
 
     private void generateByTables(String packageName, String... tableNames) {
         GlobalConfig config = new GlobalConfig();
-        String dbUrl = "jdbc:mysql://localhost:3306/mybatis-plus" ;
+        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" );
+            .setUsername("root")
+            .setPassword("")
+            .setDriverName("com.mysql.jdbc.Driver");
         StrategyConfig strategyConfig = new StrategyConfig();
         strategyConfig
             .setCapitalMode(true)
@@ -94,11 +94,11 @@ public class CodeGeneratorTest {
             .setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
         config.setActiveRecord(false)
             .setIdType(tableIdType)
-            .setAuthor("K神带你飞" )
-            .setOutputDir("d:\\codeGen" )
+            .setAuthor("K神带你飞")
+            .setOutputDir("d:\\codeGen")
             .setFileOverride(true);
         if (!serviceClassNameStartWithI) {
-            config.setServiceName("%sService" );
+            config.setServiceName("%sService");
         }
         new AutoGenerator().setGlobalConfig(config)
             .setDataSource(dataSourceConfig)
@@ -106,8 +106,8 @@ public class CodeGeneratorTest {
             .setPackageInfo(
                 new PackageConfig()
                     .setParent(packageName)
-                    .setController("controller" )
-                    .setEntity("entity" )
+                    .setController("controller")
+                    .setEntity("entity")
             ).execute();
     }
 }

+ 5 - 5
mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/GeneratorTest.java

@@ -21,11 +21,11 @@ public class GeneratorTest {
     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请输入:" );
+        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;
         // 现在有输入数据

+ 22 - 0
mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/MyPostgreSqlQuery.java

@@ -0,0 +1,22 @@
+package com.baomidou.mybatisplus.test.generator;
+
+import com.baomidou.mybatisplus.generator.config.querys.PostgreSqlQuery;
+
+public class MyPostgreSqlQuery extends PostgreSqlQuery {
+
+
+    @Override
+    public String tableFieldsSql() {
+        // 固定 abc  def 内容,实际可以查询字段大小等信息
+        return "SELECT 1 AS abc, 2 AS def, A.attname AS name, format_type(A.atttypid, A.atttypmod) AS type,col_description(A.attrelid, A.attnum) AS comment, (CASE C.contype WHEN 'p' THEN 'PRI' ELSE '' END) AS key " +
+            "FROM pg_attribute A LEFT JOIN pg_constraint C ON A.attnum = C.conkey[1] AND A.attrelid = C.conrelid " +
+            "WHERE  A.attrelid = '%s.%s'::regclass AND A.attnum > 0 AND NOT A.attisdropped ORDER  BY A.attnum";
+    }
+
+
+    @Override
+    public String[] fieldCustom() {
+        // 返回自定义查询字段
+        return new String[]{"abc", "def"};
+    }
+}

+ 16 - 16
mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/MysqlGenerator.java

@@ -1,4 +1,4 @@
-/*
+/**
  * Copyright (c) 2011-2016, hubin (jobob@qq.com).
  * <p>
  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
@@ -57,20 +57,20 @@ public class MysqlGenerator extends GeneratorTest {
         int result = scanner();
         // 自定义需要填充的字段
         List<TableFill> tableFillList = new ArrayList<>();
-        tableFillList.add(new TableFill("ASDD_SS" , FieldFill.INSERT_UPDATE));
+        tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE));
 
         // 代码生成器
         AutoGenerator mpg = new AutoGenerator().setGlobalConfig(
             // 全局配置
             new GlobalConfig()
-                .setOutputDir("/develop/code/" )//输出目录
+                .setOutputDir("/develop/code/")//输出目录
                 .setFileOverride(true)// 是否覆盖文件
                 .setActiveRecord(true)// 开启 activeRecord 模式
                 .setEnableCache(false)// XML 二级缓存
                 .setBaseResultMap(true)// XML ResultMap
                 .setBaseColumnList(true)// XML columList
                 //.setKotlin(true) 是否生成 kotlin 代码
-                .setAuthor("Yanghu" )
+                .setAuthor("Yanghu")
             // 自定义文件命名,注意 %s 会自动填充表实体属性!
             // .setMapperName("%sDao")
             // .setXmlName("%sDao")
@@ -92,16 +92,16 @@ public class MysqlGenerator extends GeneratorTest {
                         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" )
+                .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_"})// 此处可以修改为您的表前缀
+                .setTablePrefix(new String[]{"bmd_", "mp_"})// 此处可以修改为您的表前缀
                 .setNaming(NamingStrategy.underline_to_camel)// 表名生成策略
                 // .setInclude(new String[] { "user" }) // 需要生成的表
                 // .setExclude(new String[]{"test"}) // 排除生成的表
@@ -133,24 +133,24 @@ public class MysqlGenerator extends GeneratorTest {
         ).setPackageInfo(
             // 包配置
             new PackageConfig()
-                .setModuleName("test" )
-                .setParent("com.baomidou" )// 自定义包路径
-                .setController("controller" )// 这里是控制器包名,默认 web
+                .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" );
+                    map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                     this.setMap(map);
                 }
             }.setFileOutConfigList(Collections.<FileOutConfig>singletonList(new FileOutConfig(
-                "/templates/mapper.xml" + ((1 == result) ? ".ftl" : ".vm" )) {
+                "/templates/mapper.xml" + ((1 == result) ? ".ftl" : ".vm")) {
                 // 自定义输出文件目录
                 @Override
                 public String outputFile(TableInfo tableInfo) {
-                    return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml" ;
+                    return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";
                 }
             }))
         ).setTemplate(
@@ -172,7 +172,7 @@ public class MysqlGenerator extends GeneratorTest {
         mpg.execute();
 
         // 打印注入设置,这里演示模板里面怎么获取注入内容【可无】
-        System.err.println(mpg.getCfg().getMap().get("abc" ));
+        System.err.println(mpg.getCfg().getMap().get("abc"));
     }
 
 }

+ 18 - 20
mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/PostgreSQLGenerator.java

@@ -5,7 +5,6 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import com.baomidou.mybatisplus.annotation.FieldFill;
 import com.baomidou.mybatisplus.generator.AutoGenerator;
 import com.baomidou.mybatisplus.generator.InjectionConfig;
 import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
@@ -14,7 +13,6 @@ 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.converts.OracleTypeConvert;
-import com.baomidou.mybatisplus.generator.config.po.TableFill;
 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
 import com.baomidou.mybatisplus.generator.config.rules.DbType;
@@ -37,14 +35,14 @@ public class PostgreSQLGenerator extends GeneratorTest {
 
         // 全局配置
         GlobalConfig gc = new GlobalConfig();
-        gc.setOutputDir("D://" );
+        gc.setOutputDir("D://");
         gc.setFileOverride(true);
         gc.setActiveRecord(true);// 开启 activeRecord 模式
         gc.setEnableCache(false);// XML 二级缓存
         gc.setBaseResultMap(true);// XML ResultMap
         gc.setBaseColumnList(false);// XML columList
         //gc.setKotlin(true) 是否生成 kotlin 代码
-        gc.setAuthor("hubin" );
+        gc.setAuthor("hubin");
 
         // 自定义文件命名,注意 %s 会自动填充表实体属性!
         // gc.setMapperName("%sDao");
@@ -56,7 +54,7 @@ public class PostgreSQLGenerator extends GeneratorTest {
 
         // 数据源配置
         DataSourceConfig dsc = new DataSourceConfig();
-        dsc.setSchemaname("public" );// 指定 SCHEMA
+        dsc.setSchemaname("public");// 指定 SCHEMA
         dsc.setDbType(DbType.POSTGRE_SQL);
         dsc.setTypeConvert(new OracleTypeConvert() {
             // 自定义数据库表字段类型转换【可选】
@@ -66,17 +64,20 @@ public class PostgreSQLGenerator extends GeneratorTest {
                 return super.processTypeConvert(fieldType);
             }
         });
-        dsc.setDriverName("org.postgresql.Driver" );
-        dsc.setUsername("postgres" );
-        dsc.setPassword("521" );
-        dsc.setUrl("jdbc:postgresql://localhost:5432/mybatis-plus" );
+        // 自定义数据库信息查询
+        dsc.setDbQuery(new MyPostgreSqlQuery());
+        dsc.setDriverName("org.postgresql.Driver");
+        dsc.setUsername("postgres");
+        dsc.setPassword("521");
+        dsc.setUrl("jdbc:postgresql://localhost:5432/mybatis-plus");
         mpg.setDataSource(dsc);
 
         // 策略配置
         StrategyConfig strategy = new StrategyConfig();
         // strategy.setCapitalMode(true);// 全局大写命名
         // strategy.setDbColumnUnderline(true);//全局下划线命名
-        strategy.setTablePrefix(new String[]{"bmd_" , "mp_"});// 此处可以修改为您的表前缀
+        strategy.setTablePrefix(new String[]{"bmd_", "mp_"});// 此处可以修改为您的表前缀
+        strategy.setFieldPrefix(new String[]{"A_"});
         strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
         strategy.setColumnNaming(NamingStrategy.underline_to_camel);// 允许字段策略独立设置,默认为 naming 策略
         // strategy.setInclude(new String[] { "user" }); // 需要生成的表
@@ -99,16 +100,13 @@ public class PostgreSQLGenerator extends GeneratorTest {
         // 【实体】是否为构建者模型(默认 false)
         // public User setName(String name) {this.name = name; return this;}
         // strategy.setEntityBuliderModel(true);
-        List tableFillList = new ArrayList();
-        tableFillList.add(new TableFill("name", FieldFill.INSERT));
-        strategy.setTableFillList(tableFillList);
         mpg.setStrategy(strategy);
 
         // 包配置
         PackageConfig pc = new PackageConfig();
-        pc.setModuleName("test" );
-        pc.setParent("com.baomidou" );// 自定义包路径
-        pc.setController("controller" );// 这里是控制器包名,默认 web
+        pc.setModuleName("test");
+        pc.setParent("com.baomidou");// 自定义包路径
+        pc.setController("controller");// 这里是控制器包名,默认 web
         mpg.setPackageInfo(pc);
 
         // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
@@ -116,16 +114,16 @@ public class PostgreSQLGenerator extends GeneratorTest {
             @Override
             public void initMap() {
                 Map<String, Object> map = new HashMap<>();
-                map.put("abc" , this.getConfig().getGlobalConfig().getAuthor() + "-mp" );
+                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                 this.setMap(map);
             }
         };
         List<FileOutConfig> focList = new ArrayList<>();
-        focList.add(new FileOutConfig("/templates/dto.java" + ((1 == result) ? ".ftl" : ".vm" )) {
+        focList.add(new FileOutConfig("/templates/dto.java" + ((1 == result) ? ".ftl" : ".vm")) {
             @Override
             public String outputFile(TableInfo tableInfo) {
                 // 自定义输入文件名称
-                return "D://test/my_" + tableInfo.getEntityName() + ".java" ;
+                return "D://test/my_" + tableInfo.getEntityName() + ".java";
             }
         });
         cfg.setFileOutConfigList(focList);
@@ -148,7 +146,7 @@ public class PostgreSQLGenerator extends GeneratorTest {
         }
         mpg.execute();
         // 打印注入设置
-        System.err.println(mpg.getCfg().getMap().get("abc" ));
+        System.err.println(mpg.getCfg().getMap().get("abc"));
     }
 
 }

+ 14 - 14
mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/SQLServerGenerator.java

@@ -35,14 +35,14 @@ public class SQLServerGenerator extends GeneratorTest {
 
         // 全局配置
         GlobalConfig gc = new GlobalConfig();
-        gc.setOutputDir("D://" );
+        gc.setOutputDir("D://");
         gc.setFileOverride(true);
         gc.setActiveRecord(true);// 开启 activeRecord 模式
         gc.setEnableCache(false);// XML 二级缓存
         gc.setBaseResultMap(true);// XML ResultMap
         gc.setBaseColumnList(false);// XML columList
         //gc.setKotlin(true) 是否生成 kotlin 代码
-        gc.setAuthor("nieqiurong" );
+        gc.setAuthor("nieqiurong");
 
         // 自定义文件命名,注意 %s 会自动填充表实体属性!
         // gc.setMapperName("%sDao");
@@ -63,17 +63,17 @@ public class SQLServerGenerator extends GeneratorTest {
                 return super.processTypeConvert(fieldType);
             }
         });
-        dsc.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver" );
-        dsc.setUsername("sa" );
-        dsc.setPassword("nieqiuqiu" );
-        dsc.setUrl("jdbc:sqlserver://192.168.1.105:1433;databaseName=mybatis-plus" );
+        dsc.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
+        dsc.setUsername("sa");
+        dsc.setPassword("nieqiuqiu");
+        dsc.setUrl("jdbc:sqlserver://192.168.1.105:1433;databaseName=mybatis-plus");
         mpg.setDataSource(dsc);
 
         // 策略配置
         StrategyConfig strategy = new StrategyConfig();
         // strategy.setCapitalMode(true);// 全局大写命名
         // strategy.setDbColumnUnderline(true);//全局下划线命名
-        strategy.setTablePrefix(new String[]{"bmd_" , "mp_"});// 此处可以修改为您的表前缀
+        strategy.setTablePrefix(new String[]{"bmd_", "mp_"});// 此处可以修改为您的表前缀
         strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
         // strategy.setInclude(new String[] { "user" }); // 需要生成的表
         // strategy.setExclude(new String[]{"test"}); // 排除生成的表
@@ -99,9 +99,9 @@ public class SQLServerGenerator extends GeneratorTest {
 
         // 包配置
         PackageConfig pc = new PackageConfig();
-        pc.setModuleName("test" );
-        pc.setParent("com.baomidou" );// 自定义包路径
-        pc.setController("controller" );// 这里是控制器包名,默认 web
+        pc.setModuleName("test");
+        pc.setParent("com.baomidou");// 自定义包路径
+        pc.setController("controller");// 这里是控制器包名,默认 web
         mpg.setPackageInfo(pc);
 
         // 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
@@ -109,16 +109,16 @@ public class SQLServerGenerator extends GeneratorTest {
             @Override
             public void initMap() {
                 Map<String, Object> map = new HashMap<>();
-                map.put("abc" , this.getConfig().getGlobalConfig().getAuthor() + "-mp" );
+                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                 this.setMap(map);
             }
         };
         List<FileOutConfig> focList = new ArrayList<>();
-        focList.add(new FileOutConfig("/templates/entity.java" + ((1 == result) ? ".ftl" : ".vm" )) {
+        focList.add(new FileOutConfig("/templates/entity.java" + ((1 == result) ? ".ftl" : ".vm")) {
             @Override
             public String outputFile(TableInfo tableInfo) {
                 // 自定义输入文件名称
-                return "D://my_" + tableInfo.getEntityName() + ".java" ;
+                return "D://my_" + tableInfo.getEntityName() + ".java";
             }
         });
         cfg.setFileOutConfigList(focList);
@@ -140,7 +140,7 @@ public class SQLServerGenerator extends GeneratorTest {
         }
         mpg.execute();
         // 打印注入设置
-        System.err.println(mpg.getCfg().getMap().get("abc" ));
+        System.err.println(mpg.getCfg().getMap().get("abc"));
     }
 
 }

+ 8 - 2
mybatis-plus-generator/src/test/resources/templates/dto.java.ftl

@@ -3,9 +3,15 @@ package ${package.Entity};
 
 /**
  * <p>
- * 测试自定义DTO模板 ${table.comment}
- * </p>
+    * 测试自定义DTO模板 ${table.comment}
+    * </p>
  *
  * 测试注入 ${cfg.abc}
  */
 
+
+// 自定义的查询内容
+<#list table.fields as field>
+    自定义 abc 内容: ${field.customMap.abc}
+    自定义 def 内容: ${field.customMap.def}
+</#list>

+ 6 - 1
mybatis-plus-generator/src/test/resources/templates/dto.java.vm

@@ -1,9 +1,14 @@
 package ${package.Entity};
 
-
 /**
  * <p>
  * 测试自定义DTO模板  $!{table.comment}
  * </p>
  * 测试注入 ${cfg.abc}
  */
+
+// 自定义的查询内容
+#foreach($field in ${table.fields})
+自定义 abc 内容: ${field.customMap.abc}
+    自定义 def 内容: ${field.customMap.def}
+#end