Browse Source

重构生成器.

nieqiurong 4 years ago
parent
commit
1b06d0fe70

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

@@ -53,19 +53,19 @@ public class AutoGenerator {
     /**
     /**
      * 数据库表配置
      * 数据库表配置
      */
      */
-    private StrategyConfig strategy = new StrategyConfig();
+    private StrategyConfig strategy;
     /**
     /**
      * 包 相关配置
      * 包 相关配置
      */
      */
-    private PackageConfig packageInfo = new PackageConfig();
+    private PackageConfig packageInfo;
     /**
     /**
      * 模板 相关配置
      * 模板 相关配置
      */
      */
-    private TemplateConfig template = new TemplateConfig();
+    private TemplateConfig template;
     /**
     /**
      * 全局 相关配置
      * 全局 相关配置
      */
      */
-    private GlobalConfig globalConfig = new GlobalConfig();
+    private GlobalConfig globalConfig;
     /**
     /**
      * 模板引擎
      * 模板引擎
      */
      */

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

@@ -86,7 +86,7 @@ public class DataSourceConfig {
             dbQuery = Optional.ofNullable(dbQueryRegistry.getDbQuery(dbType))
             dbQuery = Optional.ofNullable(dbQueryRegistry.getDbQuery(dbType))
                 .orElseGet(() -> dbQueryRegistry.getDbQuery(DbType.MYSQL));
                 .orElseGet(() -> dbQueryRegistry.getDbQuery(DbType.MYSQL));
         }
         }
-        return new DecoratorDbQuery(dbQuery, this);
+        return dbQuery;
     }
     }
 
 
     /**
     /**
@@ -161,8 +161,10 @@ public class DataSourceConfig {
 
 
     /**
     /**
      * 创建数据库连接对象
      * 创建数据库连接对象
+     * 这方法建议只调用一次,毕竟只是代码生成,用一个连接就行。
      *
      *
      * @return Connection
      * @return Connection
+     * @see DecoratorDbQuery#getConnection()
      */
      */
     public Connection getConn() {
     public Connection getConn() {
         Connection conn;
         Connection conn;

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

@@ -66,10 +66,7 @@ public interface INameConvert {
 
 
         @Override
         @Override
         public String propertyNameConvert(TableField field) {
         public String propertyNameConvert(TableField field) {
-            String name = processName(field.getName(), strategyConfig.getNaming(), strategyConfig.getTablePrefix());
-            //TODO 暂时先放在这里调用,后面要改掉才行!!!!!
-            field.setPropertyName(strategyConfig, name);
-            return name;
+            return processName(field.getName(), strategyConfig.getNaming(), strategyConfig.getTablePrefix());
         }
         }
 
 
         private String processName(String name, NamingStrategy strategy, Set<String> prefix) {
         private String processName(String name, NamingStrategy strategy, Set<String> prefix) {

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

@@ -260,12 +260,49 @@ public class StrategyConfig {
         return this;
         return this;
     }
     }
 
 
+    /**
+     * @param fieldName 字段名
+     * @return 是否匹配
+     * @see #matchSuperEntityColumns(String)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public boolean includeSuperEntityColumns(String fieldName) {
     public boolean includeSuperEntityColumns(String fieldName) {
+        // 公共字段判断忽略大小写【 部分数据库大小写不敏感 】
+        return matchSuperEntityColumns(fieldName);
+    }
+
+    /**
+     * 匹配父类字段(忽略大小写)
+     *
+     * @param fieldName 字段名
+     * @return 是否匹配
+     * @since 3.4.1
+     */
+    public boolean matchSuperEntityColumns(String fieldName) {
         // 公共字段判断忽略大小写【 部分数据库大小写不敏感 】
         // 公共字段判断忽略大小写【 部分数据库大小写不敏感 】
         return superEntityColumns.stream().anyMatch(e -> e.equalsIgnoreCase(fieldName));
         return superEntityColumns.stream().anyMatch(e -> e.equalsIgnoreCase(fieldName));
     }
     }
 
 
+    /**
+     * @param superEntityColumns 父类字段
+     * @return this
+     * @see #addSuperEntityColumns(String...)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public StrategyConfig setSuperEntityColumns(String... superEntityColumns) {
     public StrategyConfig setSuperEntityColumns(String... superEntityColumns) {
+        return addSuperEntityColumns(superEntityColumns);
+    }
+
+    /**
+     * 添加父类公共字段
+     *
+     * @param superEntityColumns 父类字段(数据库字段列名)
+     * @return this
+     * @since 3.4.1
+     */
+    public StrategyConfig addSuperEntityColumns(String... superEntityColumns) {
         this.superEntityColumns.addAll(Arrays.asList(superEntityColumns));
         this.superEntityColumns.addAll(Arrays.asList(superEntityColumns));
         return this;
         return this;
     }
     }
@@ -361,7 +398,7 @@ public class StrategyConfig {
      * </p>
      * </p>
      *
      *
      * @param clazz 实体父类 Class
      * @param clazz 实体父类 Class
-     * @return
+     * @return this
      */
      */
     public StrategyConfig setSuperEntityClass(Class<?> clazz) {
     public StrategyConfig setSuperEntityClass(Class<?> clazz) {
         this.superEntityClass = clazz.getName();
         this.superEntityClass = clazz.getName();
@@ -376,7 +413,7 @@ public class StrategyConfig {
      *
      *
      * @param clazz        实体父类 Class
      * @param clazz        实体父类 Class
      * @param columnNaming 字段命名策略
      * @param columnNaming 字段命名策略
-     * @return
+     * @return this
      */
      */
     public StrategyConfig setSuperEntityClass(Class<?> clazz, NamingStrategy columnNaming) {
     public StrategyConfig setSuperEntityClass(Class<?> clazz, NamingStrategy columnNaming) {
         this.columnNaming = columnNaming;
         this.columnNaming = columnNaming;
@@ -419,6 +456,7 @@ public class StrategyConfig {
      *
      *
      * @param tableFillList tableFillList
      * @param tableFillList tableFillList
      * @see #addTableFills(TableFill...)
      * @see #addTableFills(TableFill...)
+     * @see #addTableFills(List)
      * @deprecated 3.4.1
      * @deprecated 3.4.1
      */
      */
     @Deprecated
     @Deprecated
@@ -438,6 +476,18 @@ public class StrategyConfig {
         return this;
         return this;
     }
     }
 
 
+    /**
+     * 添加表字段填充
+     *
+     * @param tableFillList 填充字段集合
+     * @return this
+     * @since 3.4.1
+     */
+    public StrategyConfig addTableFills(List<TableFill> tableFillList) {
+        this.tableFillList.addAll(tableFillList);
+        return this;
+    }
+
     /**
     /**
      * <p>
      * <p>
      * 父类 Class 反射属性转换为公共字段
      * 父类 Class 反射属性转换为公共字段
@@ -524,13 +574,12 @@ public class StrategyConfig {
     /**
     /**
      * 表名匹配
      * 表名匹配
      *
      *
-     * @param setTableName 设置表名
-     * @param dbTableName  数据库表单
-     * @return ignore
+     * @param matchTableName 匹配表名
+     * @param dbTableName    数据库表名
+     * @return 是否匹配
      */
      */
-    private boolean tableNameMatches(String setTableName, String dbTableName) {
-        return setTableName.equalsIgnoreCase(dbTableName)
-            || StringUtils.matches(setTableName, dbTableName);
+    private boolean tableNameMatches(String matchTableName, String dbTableName) {
+        return matchTableName.equalsIgnoreCase(dbTableName) || StringUtils.matches(matchTableName, dbTableName);
     }
     }
 
 
 }
 }

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

@@ -87,7 +87,7 @@ public class TemplateConfig {
         return this;
         return this;
     }
     }
 
 
-    public Map<String, String> initTemplate(GlobalConfig globalConfig, Map<String, String> packageInfo) {
+    public Map<String, String> getPathInfo(GlobalConfig globalConfig, Map<String, String> packageInfo) {
         Map<String, String> initMap = CollectionUtils.newHashMapWithExpectedSize(6);
         Map<String, String> initMap = CollectionUtils.newHashMapWithExpectedSize(6);
         String outputDir = globalConfig.getOutputDir();
         String outputDir = globalConfig.getOutputDir();
         setPathInfo(initMap, packageInfo, this.getEntity(globalConfig.isKotlin()), outputDir, ConstVal.ENTITY_PATH, ConstVal.ENTITY);
         setPathInfo(initMap, packageInfo, this.getEntity(globalConfig.isKotlin()), outputDir, ConstVal.ENTITY_PATH, ConstVal.ENTITY);

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

@@ -16,6 +16,7 @@
 package com.baomidou.mybatisplus.generator.config.builder;
 package com.baomidou.mybatisplus.generator.config.builder;
 
 
 import com.baomidou.mybatisplus.annotation.DbType;
 import com.baomidou.mybatisplus.annotation.DbType;
+import com.baomidou.mybatisplus.core.toolkit.StringPool;
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.generator.InjectionConfig;
 import com.baomidou.mybatisplus.generator.InjectionConfig;
 import com.baomidou.mybatisplus.generator.config.*;
 import com.baomidou.mybatisplus.generator.config.*;
@@ -29,9 +30,6 @@ import lombok.Getter;
 import lombok.Setter;
 import lombok.Setter;
 import lombok.experimental.Accessors;
 import lombok.experimental.Accessors;
 
 
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.SQLException;
 import java.util.*;
 import java.util.*;
 import java.util.regex.Pattern;
 import java.util.regex.Pattern;
@@ -58,12 +56,6 @@ public class ConfigBuilder {
     @Getter(value = AccessLevel.NONE)
     @Getter(value = AccessLevel.NONE)
     @Setter(value = AccessLevel.NONE)
     @Setter(value = AccessLevel.NONE)
     private final DataSourceConfig dataSourceConfig;
     private final DataSourceConfig dataSourceConfig;
-    /**
-     * SQL连接
-     */
-    @Getter(value = AccessLevel.NONE)
-    @Setter(value = AccessLevel.NONE)
-    private final Connection connection;
     /**
     /**
      * 数据库表信息
      * 数据库表信息
      */
      */
@@ -110,15 +102,16 @@ public class ConfigBuilder {
      */
      */
     public ConfigBuilder(PackageConfig packageConfig, DataSourceConfig dataSourceConfig, StrategyConfig strategyConfig,
     public ConfigBuilder(PackageConfig packageConfig, DataSourceConfig dataSourceConfig, StrategyConfig strategyConfig,
                          TemplateConfig template, GlobalConfig globalConfig) {
                          TemplateConfig template, GlobalConfig globalConfig) {
-        this.connection = dataSourceConfig.getConn();
+        this.strategyConfig = Optional.ofNullable(strategyConfig).orElseGet(StrategyConfig::new);
+        //TODO 先把验证插在这里,后续改成build构建的话在build的时候验证
+        this.strategyConfig.validate();
         this.dataSourceConfig = dataSourceConfig;
         this.dataSourceConfig = dataSourceConfig;
-        this.dbQuery = (DecoratorDbQuery) dataSourceConfig.getDbQuery();
-        this.globalConfig = globalConfig;
-        this.template = template;
+        this.dbQuery = new DecoratorDbQuery(dataSourceConfig.getDbQuery(), dataSourceConfig, strategyConfig);
+        this.globalConfig = Optional.ofNullable(globalConfig).orElseGet(GlobalConfig::new);
+        this.template = Optional.ofNullable(template).orElseGet(TemplateConfig::new);
+        packageConfig = Optional.ofNullable(packageConfig).orElseGet(PackageConfig::new);
         this.packageInfo.putAll(packageConfig.initPackageInfo());
         this.packageInfo.putAll(packageConfig.initPackageInfo());
-        this.pathInfo.putAll(Optional.ofNullable(packageConfig.getPathInfo()).orElseGet(() -> this.template.initTemplate(this.globalConfig, packageInfo)));
-        this.strategyConfig = strategyConfig;
-        this.strategyConfig.validate();
+        this.pathInfo.putAll(Optional.ofNullable(packageConfig.getPathInfo()).orElseGet(() -> this.template.getPathInfo(this.globalConfig, packageInfo)));
         this.tableInfoList.addAll(getTablesInfo());
         this.tableInfoList.addAll(getTablesInfo());
         processTable();
         processTable();
     }
     }
@@ -176,55 +169,29 @@ public class ConfigBuilder {
         //需要反向生成或排除的表信息
         //需要反向生成或排除的表信息
         List<TableInfo> includeTableList = new ArrayList<>();
         List<TableInfo> includeTableList = new ArrayList<>();
         List<TableInfo> excludeTableList = new ArrayList<>();
         List<TableInfo> excludeTableList = new ArrayList<>();
-
         try {
         try {
-            String tablesSql = dbQuery.tablesSql();
-            StringBuilder sql = new StringBuilder(tablesSql);
-            if (strategyConfig.isEnableSqlFilter()) {
-                if (strategyConfig.getLikeTable() != null) {
-                    sql.append(" AND ").append(dbQuery.tableName()).append(" LIKE '").append(strategyConfig.getLikeTable().getValue()).append("'");
-                } else if (strategyConfig.getNotLikeTable() != null) {
-                    sql.append(" AND ").append(dbQuery.tableName()).append(" NOT LIKE '").append(strategyConfig.getNotLikeTable().getValue()).append("'");
-                }
-                if (isInclude) {
-                    sql.append(" AND ").append(dbQuery.tableName()).append(" IN (")
-                        .append(strategyConfig.getInclude().stream().map(tb -> "'" + tb + "'").collect(Collectors.joining(","))).append(")");
-                } else if (isExclude) {
-                    sql.append(" AND ").append(dbQuery.tableName()).append(" NOT IN (")
-                        .append(strategyConfig.getExclude().stream().map(tb -> "'" + tb + "'").collect(Collectors.joining(","))).append(")");
-                }
-            }
-            TableInfo tableInfo;
-            try (PreparedStatement preparedStatement = connection.prepareStatement(sql.toString());
-                 ResultSet results = preparedStatement.executeQuery()) {
-                while (results.next()) {
-                    final String tableName = results.getString(dbQuery.tableName());
-                    if (StringUtils.isBlank(tableName)) {
-                        System.err.println("当前数据库为空!!!");
-                        continue;
-                    }
-                    tableInfo = new TableInfo();
+            dbQuery.query(dbQuery.tablesSql(), resultSetWrapper -> {
+                String tableName = resultSetWrapper.getStringResult(dbQuery.tableName());
+                if (StringUtils.isNotBlank(tableName)) {
+                    TableInfo tableInfo = new TableInfo();
                     tableInfo.setName(tableName);
                     tableInfo.setName(tableName);
-                    String tableComment = dbQuery.getTableComment(results);
-                    if (strategyConfig.isSkipView() && "VIEW".equals(tableComment)) {
-                        // 跳过视图
-                        continue;
-                    }
-                    tableInfo.setComment(tableComment);
-                    if (isInclude && strategyConfig.matchIncludeTable(tableName)) {
-                        includeTableList.add(tableInfo);
-                    } else if (isExclude && strategyConfig.matchExcludeTable(tableName)) {
-                        excludeTableList.add(tableInfo);
+                    String tableComment = resultSetWrapper.getTableComment();
+                    // 跳过视图
+                    if (!(strategyConfig.isSkipView() && "VIEW".equals(tableComment))) {
+                        tableInfo.setComment(tableComment);
+                        if (isInclude && strategyConfig.matchIncludeTable(tableName)) {
+                            includeTableList.add(tableInfo);
+                        } else if (isExclude && strategyConfig.matchExcludeTable(tableName)) {
+                            excludeTableList.add(tableInfo);
+                        }
+                        tableList.add(tableInfo);
                     }
                     }
-                    tableList.add(tableInfo);
                 }
                 }
-            }
+            });
             //TODO 我要把这个打印不存在表的功能和正则匹配功能删掉,就算是苗老板来了也拦不住的那种
             //TODO 我要把这个打印不存在表的功能和正则匹配功能删掉,就算是苗老板来了也拦不住的那种
             if (isExclude || isInclude) {
             if (isExclude || isInclude) {
-                Set<String> notExistTables = new HashSet<>();
-                notExistTables.addAll(strategyConfig.getExclude());
-                notExistTables.addAll(strategyConfig.getInclude());
-                notExistTables = notExistTables.stream().filter(s -> !REGX.matcher(s).find()).collect(Collectors.toSet());
+                Set<String> notExistTables = new HashSet<>(isExclude ? strategyConfig.getExclude() : strategyConfig.getInclude())
+                    .stream().filter(s -> !REGX.matcher(s).find()).collect(Collectors.toSet());
                 // 将已经存在的表移除,获取配置中数据库不存在的表
                 // 将已经存在的表移除,获取配置中数据库不存在的表
                 for (TableInfo tabInfo : tableList) {
                 for (TableInfo tabInfo : tableList) {
                     if (notExistTables.isEmpty()) {
                     if (notExistTables.isEmpty()) {
@@ -239,7 +206,8 @@ public class ConfigBuilder {
                 if (isExclude) {
                 if (isExclude) {
                     tableList.removeAll(excludeTableList);
                     tableList.removeAll(excludeTableList);
                 } else {
                 } else {
-                    tableList = includeTableList;
+                    tableList.clear();
+                    tableList.addAll(includeTableList);
                 }
                 }
             }
             }
             // 性能优化,只处理需执行表字段 github issues/219
             // 性能优化,只处理需执行表字段 github issues/219
@@ -254,9 +222,8 @@ public class ConfigBuilder {
      * 将字段信息与表信息关联
      * 将字段信息与表信息关联
      *
      *
      * @param tableInfo 表信息
      * @param tableInfo 表信息
-     * @return ignore
      */
      */
-    private TableInfo convertTableFields(TableInfo tableInfo) {
+    private void convertTableFields(TableInfo tableInfo) {
         List<TableField> fieldList = new ArrayList<>();
         List<TableField> fieldList = new ArrayList<>();
         List<TableField> commonFieldList = new ArrayList<>();
         List<TableField> commonFieldList = new ArrayList<>();
         DbType dbType = this.dataSourceConfig.getDbType();
         DbType dbType = this.dataSourceConfig.getDbType();
@@ -265,73 +232,63 @@ public class ConfigBuilder {
             String tableFieldsSql = dbQuery.tableFieldsSql(tableName);
             String tableFieldsSql = dbQuery.tableFieldsSql(tableName);
             Set<String> h2PkColumns = new HashSet<>();
             Set<String> h2PkColumns = new HashSet<>();
             if (DbType.H2 == dbType) {
             if (DbType.H2 == dbType) {
-                try (PreparedStatement pkQueryStmt = connection.prepareStatement(String.format(H2Query.PK_QUERY_SQL, tableName));
-                     ResultSet pkResults = pkQueryStmt.executeQuery()) {
-                    while (pkResults.next()) {
-                        String primaryKey = pkResults.getString(dbQuery.fieldKey());
-                        if (Boolean.parseBoolean(primaryKey)) {
-                            h2PkColumns.add(pkResults.getString(dbQuery.fieldName()));
-                        }
+                dbQuery.query(String.format(H2Query.PK_QUERY_SQL, tableName), resultWrapper -> {
+                    String primaryKey = resultWrapper.getStringResult(dbQuery.fieldKey());
+                    if (Boolean.parseBoolean(primaryKey)) {
+                        h2PkColumns.add(resultWrapper.getStringResult(dbQuery.fieldName()));
                     }
                     }
-                }
+                });
             }
             }
-            try (
-                PreparedStatement preparedStatement = connection.prepareStatement(tableFieldsSql);
-                ResultSet results = preparedStatement.executeQuery()) {
-                while (results.next()) {
-                    TableField field = new TableField();
-                    String columnName = results.getString(dbQuery.fieldName());
-                    // 避免多重主键设置,目前只取第一个找到ID,并放到list中的索引为0的位置
-                    boolean isId;
-                    if (DbType.H2 == dbType) {
-                        isId = h2PkColumns.contains(columnName);
+            dbQuery.query(tableFieldsSql, resultSetWrapper -> {
+                TableField field = new TableField();
+                String columnName = resultSetWrapper.getStringResult(dbQuery.fieldName());
+                // 避免多重主键设置,目前只取第一个找到ID,并放到list中的索引为0的位置
+                boolean isId;
+                if (DbType.H2 == dbType) {
+                    isId = h2PkColumns.contains(columnName);
+                } else {
+                    String key = resultSetWrapper.getStringResult(dbQuery.fieldKey());
+                    if (DbType.DB2 == dbType || DbType.SQLITE == dbType) {
+                        isId = StringUtils.isNotBlank(key) && "1".equals(key);
                     } else {
                     } else {
-                        String key = results.getString(dbQuery.fieldKey());
-                        if (DbType.DB2 == dbType || DbType.SQLITE == dbType) {
-                            isId = StringUtils.isNotBlank(key) && "1".equals(key);
-                        } else {
-                            isId = StringUtils.isNotBlank(key) && "PRI".equals(key.toUpperCase());
-                        }
-                    }
-                    // 处理ID
-                    if (isId) {
-                        field.setKeyFlag(true).setKeyIdentityFlag(dbQuery.isKeyIdentity(results));
-                        tableInfo.setHavePrimaryKey(true);
-                    }
-                    String newColumnName = columnName;
-                    IKeyWordsHandler keyWordsHandler = dataSourceConfig.getKeyWordsHandler();
-                    if (keyWordsHandler != null && keyWordsHandler.isKeyWords(columnName)) {
-                        System.err.printf("当前表[%s]存在字段[%s]为数据库关键字或保留字!%n", tableName, columnName);
-                        field.setKeyWords(true);
-                        newColumnName = keyWordsHandler.formatColumn(columnName);
-                    }
-                    field.setName(columnName).setColumnName(newColumnName)
-                        .setType(results.getString(dbQuery.fieldType()))
-                        .setPropertyName(strategyConfig.getNameConvert().propertyNameConvert(field))
-                        .setColumnType(dataSourceConfig.getTypeConvert().processTypeConvert(globalConfig, field))
-                        .setComment(dbQuery.getFiledComment(results))
-                        .setCustomMap(dbQuery.getCustomFields(results));
-                    ;
-                    // 填充逻辑判断
-                    strategyConfig.getTableFillList()
-                        .stream()
-                        //忽略大写字段问题
-                        .filter(tf -> tf.getFieldName().equalsIgnoreCase(field.getName()))
-                        .findFirst().ifPresent(tf -> field.setFill(tf.getFieldFill().name()));
-                    if (strategyConfig.includeSuperEntityColumns(field.getName())) {
-                        // 跳过公共字段
-                        commonFieldList.add(field);
-                        continue;
+                        isId = StringUtils.isNotBlank(key) && "PRI".equals(key.toUpperCase());
                     }
                     }
+                }
+                // 处理ID
+                if (isId) {
+                    field.setKeyFlag(true).setKeyIdentityFlag(dbQuery.isKeyIdentity(resultSetWrapper.getResultSet()));
+                    tableInfo.setHavePrimaryKey(true);
+                }
+                String newColumnName = columnName;
+                IKeyWordsHandler keyWordsHandler = dataSourceConfig.getKeyWordsHandler();
+                if (keyWordsHandler != null && keyWordsHandler.isKeyWords(columnName)) {
+                    System.err.printf("当前表[%s]存在字段[%s]为数据库关键字或保留字!%n", tableName, columnName);
+                    field.setKeyWords(true);
+                    newColumnName = keyWordsHandler.formatColumn(columnName);
+                }
+                field.setName(columnName).setColumnName(newColumnName)
+                    .setType(resultSetWrapper.getStringResult(dbQuery.fieldType()))
+                    .setPropertyName(this.strategyConfig, strategyConfig.getNameConvert().propertyNameConvert(field))
+                    .setColumnType(dataSourceConfig.getTypeConvert().processTypeConvert(globalConfig, field))
+                    .setComment(resultSetWrapper.getFiledComment())
+                    .setCustomMap(dbQuery.getCustomFields(resultSetWrapper.getResultSet()));
+                // 填充逻辑判断
+                strategyConfig.getTableFillList().stream()
+                    //忽略大写字段问题
+                    .filter(tf -> tf.getFieldName().equalsIgnoreCase(field.getName()))
+                    .findFirst().ifPresent(tf -> field.setFill(tf.getFieldFill().name()));
+                if (strategyConfig.matchSuperEntityColumns(field.getName())) {
+                    // 跳过公共字段
+                    commonFieldList.add(field);
+                } else {
                     fieldList.add(field);
                     fieldList.add(field);
                 }
                 }
-            }
+            });
         } catch (SQLException e) {
         } catch (SQLException e) {
             throw new RuntimeException(e);
             throw new RuntimeException(e);
         }
         }
         tableInfo.addFields(fieldList);
         tableInfo.addFields(fieldList);
         tableInfo.addCommonFields(commonFieldList);
         tableInfo.addCommonFields(commonFieldList);
-        return tableInfo;
     }
     }
 
 
     /**
     /**
@@ -339,24 +296,18 @@ public class ConfigBuilder {
      *
      *
      * @param comment 注释
      * @param comment 注释
      * @return 注释
      * @return 注释
-     * @see DecoratorDbQuery#formatComment(java.lang.String)
+     * @see DecoratorDbQuery.ResultSetWrapper#formatComment(java.lang.String)
      * @since 3.4.0
      * @since 3.4.0
      * @deprecated 3.4.1
      * @deprecated 3.4.1
      */
      */
     @Deprecated
     @Deprecated
     public String formatComment(String comment) {
     public String formatComment(String comment) {
-        return dbQuery.formatComment(comment);
+        return StringUtils.isBlank(comment) ? StringPool.EMPTY : comment.replaceAll("\r\n", "\t");
     }
     }
 
 
     public void close() {
     public void close() {
         //暂时只有数据库连接需要关闭
         //暂时只有数据库连接需要关闭
-        Optional.ofNullable(connection).ifPresent((con) -> {
-            try {
-                con.close();
-            } catch (SQLException sqlException) {
-                sqlException.printStackTrace();
-            }
-        });
+        dbQuery.closeConnection();
     }
     }
 
 
     /**
     /**

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

@@ -27,7 +27,7 @@ import com.baomidou.mybatisplus.core.toolkit.sql.SqlUtils;
  */
  */
 public class LikeTable {
 public class LikeTable {
 
 
-    private String value;
+    private final String value;
 
 
     private SqlLike like = SqlLike.DEFAULT;
     private SqlLike like = SqlLike.DEFAULT;
 
 

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

@@ -88,7 +88,13 @@ public class TableField {
         return this;
         return this;
     }
     }
 
 
-    //TODO 先标记一下,后面再考虑。
+
+    /**
+     * @param propertyName 属性名称
+     * @return this
+     * @see #setPropertyName(StrategyConfig, String)
+     * @deprecated 3.4.1
+     */
     @Deprecated
     @Deprecated
     public TableField setPropertyName(String propertyName) {
     public TableField setPropertyName(String propertyName) {
         this.propertyName = propertyName;
         this.propertyName = propertyName;
@@ -96,7 +102,6 @@ public class TableField {
     }
     }
 
 
     public TableField setPropertyName(StrategyConfig strategyConfig, String propertyName) {
     public TableField setPropertyName(StrategyConfig strategyConfig, String propertyName) {
-        //TODO 这个好像是苗老板写的,有空打死他吧.
         if (strategyConfig.isEntityBooleanColumnRemoveIsPrefix()
         if (strategyConfig.isEntityBooleanColumnRemoveIsPrefix()
             && "boolean".equalsIgnoreCase(this.getPropertyType()) && this.getPropertyName().startsWith("is")) {
             && "boolean".equalsIgnoreCase(this.getPropertyType()) && this.getPropertyName().startsWith("is")) {
             this.convert = true;
             this.convert = true;

+ 112 - 37
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/querys/DecoratorDbQuery.java

@@ -21,11 +21,17 @@ import com.baomidou.mybatisplus.core.toolkit.StringPool;
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
 import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
 import com.baomidou.mybatisplus.generator.config.IDbQuery;
 import com.baomidou.mybatisplus.generator.config.IDbQuery;
+import com.baomidou.mybatisplus.generator.config.StrategyConfig;
 
 
+import java.sql.Connection;
+import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.SQLException;
 import java.util.Collections;
 import java.util.Collections;
 import java.util.Map;
 import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
 
 
 /**
 /**
  * 装饰DbQuery
  * 装饰DbQuery
@@ -36,12 +42,18 @@ public class DecoratorDbQuery extends AbstractDbQuery {
 
 
     private final IDbQuery dbQuery;
     private final IDbQuery dbQuery;
     private final DataSourceConfig dataSourceConfig;
     private final DataSourceConfig dataSourceConfig;
+    private final Connection connection;
     private final DbType dbType;
     private final DbType dbType;
+    private final StrategyConfig strategyConfig;
+    private String schema;
 
 
-    public DecoratorDbQuery(IDbQuery dbQuery, DataSourceConfig dataSourceConfig) {
+    public DecoratorDbQuery(IDbQuery dbQuery, DataSourceConfig dataSourceConfig, StrategyConfig strategyConfig) {
         this.dbQuery = dbQuery;
         this.dbQuery = dbQuery;
         this.dataSourceConfig = dataSourceConfig;
         this.dataSourceConfig = dataSourceConfig;
+        this.connection = dataSourceConfig.getConn();
         this.dbType = dataSourceConfig.getDbType();
         this.dbType = dataSourceConfig.getDbType();
+        this.strategyConfig = strategyConfig;
+        this.schema = dataSourceConfig.getSchemaName();
     }
     }
 
 
     @Override
     @Override
@@ -51,22 +63,19 @@ public class DecoratorDbQuery extends AbstractDbQuery {
         if (DbType.POSTGRE_SQL == dbType) {
         if (DbType.POSTGRE_SQL == dbType) {
             if (schema == null) {
             if (schema == null) {
                 //pg 默认 schema=public
                 //pg 默认 schema=public
-                schema = "public";
-                dataSourceConfig.setSchemaName(schema);
+                this.schema = "public";
             }
             }
             tablesSql = String.format(tablesSql, schema);
             tablesSql = String.format(tablesSql, schema);
         } else if (DbType.KINGBASE_ES == dbType) {
         } else if (DbType.KINGBASE_ES == dbType) {
             if (schema == null) {
             if (schema == null) {
                 //kingbase 默认 schema=PUBLIC
                 //kingbase 默认 schema=PUBLIC
-                schema = "PUBLIC";
-                dataSourceConfig.setSchemaName(schema);
+                this.schema = "PUBLIC";
             }
             }
             tablesSql = String.format(tablesSql, schema);
             tablesSql = String.format(tablesSql, schema);
         } else if (DbType.DB2 == dbType) {
         } else if (DbType.DB2 == dbType) {
             if (schema == null) {
             if (schema == null) {
                 //db2 默认 schema=current schema
                 //db2 默认 schema=current schema
-                schema = "current schema";
-                dataSourceConfig.setSchemaName(schema);
+                this.schema = "current schema";
             }
             }
             tablesSql = String.format(tablesSql, schema);
             tablesSql = String.format(tablesSql, schema);
         }
         }
@@ -74,11 +83,28 @@ public class DecoratorDbQuery extends AbstractDbQuery {
         else if (DbType.ORACLE == dbType) {
         else if (DbType.ORACLE == dbType) {
             //oracle 默认 schema=username
             //oracle 默认 schema=username
             if (schema == null) {
             if (schema == null) {
-                schema = dataSourceConfig.getUsername().toUpperCase();
-                dataSourceConfig.setSchemaName(schema);
+                this.schema = dataSourceConfig.getUsername().toUpperCase();
             }
             }
             tablesSql = String.format(tablesSql, schema);
             tablesSql = String.format(tablesSql, schema);
         }
         }
+        if (strategyConfig.isEnableSqlFilter()) {
+            StringBuilder sql = new StringBuilder(tablesSql);
+            boolean isInclude = strategyConfig.getInclude().size() > 0;
+            boolean isExclude = strategyConfig.getExclude().size() > 0;
+            if (strategyConfig.getLikeTable() != null) {
+                sql.append(" AND ").append(dbQuery.tableName()).append(" LIKE '").append(strategyConfig.getLikeTable().getValue()).append("'");
+            } else if (strategyConfig.getNotLikeTable() != null) {
+                sql.append(" AND ").append(dbQuery.tableName()).append(" NOT LIKE '").append(strategyConfig.getNotLikeTable().getValue()).append("'");
+            }
+            if (isInclude) {
+                sql.append(" AND ").append(dbQuery.tableName()).append(" IN (")
+                    .append(strategyConfig.getInclude().stream().map(tb -> "'" + tb + "'").collect(Collectors.joining(","))).append(")");
+            } else if (isExclude) {
+                sql.append(" AND ").append(dbQuery.tableName()).append(" NOT IN (")
+                    .append(strategyConfig.getExclude().stream().map(tb -> "'" + tb + "'").collect(Collectors.joining(","))).append(")");
+            }
+            return sql.toString();
+        }
         return tablesSql;
         return tablesSql;
     }
     }
 
 
@@ -96,19 +122,17 @@ public class DecoratorDbQuery extends AbstractDbQuery {
     public String tableFieldsSql(String tableName) {
     public String tableFieldsSql(String tableName) {
         String tableFieldsSql = this.tableFieldsSql();
         String tableFieldsSql = this.tableFieldsSql();
         if (DbType.POSTGRE_SQL == dbType) {
         if (DbType.POSTGRE_SQL == dbType) {
-            tableFieldsSql = String.format(tableFieldsSql, dataSourceConfig.getSchemaName(), tableName);
+            tableFieldsSql = String.format(tableFieldsSql, this.schema, tableName);
         } else if (DbType.KINGBASE_ES == dbType) {
         } else if (DbType.KINGBASE_ES == dbType) {
-            tableFieldsSql = String.format(tableFieldsSql, dataSourceConfig.getSchemaName(), tableName);
+            tableFieldsSql = String.format(tableFieldsSql, this.schema, tableName);
         } else if (DbType.DB2 == dbType) {
         } else if (DbType.DB2 == dbType) {
-            tableFieldsSql = String.format(tableFieldsSql, dataSourceConfig.getSchemaName(), tableName);
+            tableFieldsSql = String.format(tableFieldsSql, this.schema, tableName);
         } else if (DbType.ORACLE == dbType) {
         } else if (DbType.ORACLE == dbType) {
             tableName = tableName.toUpperCase();
             tableName = tableName.toUpperCase();
-            tableFieldsSql = String.format(tableFieldsSql.replace("#schema", dataSourceConfig.getSchemaName()), tableName);
+            tableFieldsSql = String.format(tableFieldsSql.replace("#schema", this.schema), tableName);
         } else if (DbType.DM == dbType) {
         } else if (DbType.DM == dbType) {
             tableName = tableName.toUpperCase();
             tableName = tableName.toUpperCase();
             tableFieldsSql = String.format(tableFieldsSql, tableName);
             tableFieldsSql = String.format(tableFieldsSql, tableName);
-        } else if (DbType.H2 == dbType) {
-            tableFieldsSql = String.format(tableFieldsSql, tableName);
         } else {
         } else {
             tableFieldsSql = String.format(tableFieldsSql, tableName);
             tableFieldsSql = String.format(tableFieldsSql, tableName);
         }
         }
@@ -125,10 +149,6 @@ public class DecoratorDbQuery extends AbstractDbQuery {
         return dbQuery.tableComment();
         return dbQuery.tableComment();
     }
     }
 
 
-    public String getTableComment(ResultSet resultSet) throws SQLException {
-        return getResultStringValue(resultSet, this.tableComment());
-    }
-
     @Override
     @Override
     public String fieldName() {
     public String fieldName() {
         return dbQuery.fieldName();
         return dbQuery.fieldName();
@@ -144,23 +164,6 @@ public class DecoratorDbQuery extends AbstractDbQuery {
         return dbQuery.fieldComment();
         return dbQuery.fieldComment();
     }
     }
 
 
-    public String getFiledComment(ResultSet resultSet) {
-        return getResultStringValue(resultSet, this.fieldComment());
-    }
-
-    private String getResultStringValue(ResultSet resultSet, String columnLabel) {
-        try {
-            return StringUtils.isNotBlank(columnLabel) ? StringPool.EMPTY : formatComment(resultSet.getString(columnLabel));
-        } catch (SQLException e) {
-            //ignore
-        }
-        return StringPool.EMPTY;
-    }
-
-    public String formatComment(String comment) {
-        return StringUtils.isBlank(comment) ? StringPool.EMPTY : comment.replaceAll("\r\n", "\t");
-    }
-
     @Override
     @Override
     public String fieldKey() {
     public String fieldKey() {
         return dbQuery.fieldKey();
         return dbQuery.fieldKey();
@@ -171,7 +174,7 @@ public class DecoratorDbQuery extends AbstractDbQuery {
         try {
         try {
             return dbQuery.isKeyIdentity(results);
             return dbQuery.isKeyIdentity(results);
         } catch (SQLException e) {
         } catch (SQLException e) {
-            // ignore
+            // ignore 这个看到在查H2的时候出了异常,先忽略这个异常了.
         }
         }
         return false;
         return false;
     }
     }
@@ -197,4 +200,76 @@ public class DecoratorDbQuery extends AbstractDbQuery {
         }
         }
         return Collections.emptyMap();
         return Collections.emptyMap();
     }
     }
+
+    public void query(String sql, Consumer<ResultSetWrapper> consumer) throws SQLException {
+        //TODO 先插在这里,等后面重构了#tablesSql里面的一堆默认逻辑在处理。
+        if (StringUtils.isBlank(connection.getSchema()) && StringUtils.isNotBlank(this.schema)) {
+            try {
+                connection.setSchema(schema);
+            } catch (SQLException sqlException) {
+                //这取决驱动与数据库实现,暂时忽略掉这错误.
+            }
+        }
+        PreparedStatement preparedStatement = connection.prepareStatement(sql);
+        try (ResultSet resultSet = preparedStatement.executeQuery()) {
+            while (resultSet.next()) {
+                consumer.accept(new ResultSetWrapper(resultSet, this));
+            }
+        }
+    }
+
+    public Connection getConnection() {
+        return connection;
+    }
+
+    public void closeConnection() {
+        Optional.ofNullable(connection).ifPresent((con) -> {
+            try {
+                con.close();
+            } catch (SQLException sqlException) {
+                sqlException.printStackTrace();
+            }
+        });
+    }
+
+    public static class ResultSetWrapper {
+
+        private final IDbQuery dbQuery;
+
+        private final ResultSet resultSet;
+
+        ResultSetWrapper(ResultSet resultSet, IDbQuery dbQuery) {
+            this.resultSet = resultSet;
+            this.dbQuery = dbQuery;
+        }
+
+        public ResultSet getResultSet() {
+            return resultSet;
+        }
+
+        public String getStringResult(String columnLabel) {
+            try {
+                return resultSet.getString(columnLabel);
+            } catch (SQLException sqlException) {
+                throw new RuntimeException(String.format("读取[%s]字段出错!", columnLabel), sqlException);
+            }
+        }
+
+        public String getFiledComment() {
+            return getComment(dbQuery.fieldComment());
+
+        }
+
+        private String getComment(String columnLabel) {
+            return StringUtils.isNotBlank(columnLabel) ? formatComment(getStringResult(columnLabel)) : StringPool.EMPTY;
+        }
+
+        public String getTableComment() {
+            return getComment(dbQuery.tableComment());
+        }
+
+        public String formatComment(String comment) {
+            return StringUtils.isBlank(comment) ? StringPool.EMPTY : comment.replaceAll("\r\n", "\t");
+        }
+    }
 }
 }

+ 6 - 6
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/keywords/H2KeyWordsHandler.java

@@ -27,8 +27,8 @@ import java.util.List;
  * @since 3.3.2
  * @since 3.3.2
  */
  */
 public class H2KeyWordsHandler extends BaseKeyWordsHandler {
 public class H2KeyWordsHandler extends BaseKeyWordsHandler {
-    
-    private static List<String> KEY_WORDS = new ArrayList<>(Arrays.asList(
+
+    private static final List<String> KEY_WORDS = new ArrayList<>(Arrays.asList(
         "ALL",
         "ALL",
         "AND",
         "AND",
         "ARRAY",
         "ARRAY",
@@ -110,18 +110,18 @@ public class H2KeyWordsHandler extends BaseKeyWordsHandler {
         "WINDOW",
         "WINDOW",
         "WITH"
         "WITH"
     ));
     ));
-    
+
     public H2KeyWordsHandler() {
     public H2KeyWordsHandler() {
         super(KEY_WORDS);
         super(KEY_WORDS);
     }
     }
-    
+
     public H2KeyWordsHandler(List<String> keyWords) {
     public H2KeyWordsHandler(List<String> keyWords) {
         super(keyWords);
         super(keyWords);
     }
     }
-    
+
     @Override
     @Override
     public String formatStyle() {
     public String formatStyle() {
         return "\"%s\"";
         return "\"%s\"";
     }
     }
-    
+
 }
 }

+ 6 - 6
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/keywords/MySqlKeyWordsHandler.java

@@ -27,8 +27,8 @@ import java.util.List;
  * @since 3.3.2
  * @since 3.3.2
  */
  */
 public class MySqlKeyWordsHandler extends BaseKeyWordsHandler {
 public class MySqlKeyWordsHandler extends BaseKeyWordsHandler {
-    
-    private static List<String> KEY_WORDS = new ArrayList<>(Arrays.asList(
+
+    private static final List<String> KEY_WORDS = new ArrayList<>(Arrays.asList(
         "ACCESSIBLE",
         "ACCESSIBLE",
         "ACCOUNT",
         "ACCOUNT",
         "ACTION",
         "ACTION",
@@ -651,18 +651,18 @@ public class MySqlKeyWordsHandler extends BaseKeyWordsHandler {
         "YEAR",
         "YEAR",
         "YEAR_MONTH",
         "YEAR_MONTH",
         "ZEROFILL"));
         "ZEROFILL"));
-    
+
     public MySqlKeyWordsHandler() {
     public MySqlKeyWordsHandler() {
         super(KEY_WORDS);
         super(KEY_WORDS);
     }
     }
-    
+
     public MySqlKeyWordsHandler(List<String> keyWords) {
     public MySqlKeyWordsHandler(List<String> keyWords) {
         super(keyWords);
         super(keyWords);
     }
     }
-    
+
     @Override
     @Override
     public String formatStyle() {
     public String formatStyle() {
         return "`%s`";
         return "`%s`";
     }
     }
-    
+
 }
 }

+ 6 - 6
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/keywords/PostgreSqlKeyWordsHandler.java

@@ -27,8 +27,8 @@ import java.util.List;
  * @since 3.3.2
  * @since 3.3.2
  */
  */
 public class PostgreSqlKeyWordsHandler extends BaseKeyWordsHandler {
 public class PostgreSqlKeyWordsHandler extends BaseKeyWordsHandler {
-    
-    private static List<String> KEY_WORDS = new ArrayList<>(Arrays.asList(
+
+    private static final List<String> KEY_WORDS = new ArrayList<>(Arrays.asList(
         "ALL",
         "ALL",
         "ANALYSE",
         "ANALYSE",
         "ANALYZE",
         "ANALYZE",
@@ -130,18 +130,18 @@ public class PostgreSqlKeyWordsHandler extends BaseKeyWordsHandler {
         "WINDOW",
         "WINDOW",
         "WITH"
         "WITH"
     ));
     ));
-    
+
     public PostgreSqlKeyWordsHandler() {
     public PostgreSqlKeyWordsHandler() {
         super(KEY_WORDS);
         super(KEY_WORDS);
     }
     }
-    
+
     public PostgreSqlKeyWordsHandler(List<String> keyWords) {
     public PostgreSqlKeyWordsHandler(List<String> keyWords) {
         super(keyWords);
         super(keyWords);
     }
     }
-    
+
     @Override
     @Override
     public String formatStyle() {
     public String formatStyle() {
         return "\"%s\"";
         return "\"%s\"";
     }
     }
-    
+
 }
 }