Pārlūkot izejas kodu

继续重构代码生成器.

nieqiurong 4 gadi atpakaļ
vecāks
revīzija
6f9cb835f0

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

@@ -20,10 +20,7 @@ import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
 import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
-import lombok.AccessLevel;
 import lombok.Data;
-import lombok.Getter;
-import lombok.Setter;
 import lombok.experimental.Accessors;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -48,8 +45,6 @@ public class AutoGenerator {
     /**
      * 注入配置
      */
-    @Getter(AccessLevel.NONE)
-    @Setter(AccessLevel.NONE)
     protected InjectionConfig injectionConfig;
     /**
      * 数据源配置
@@ -74,7 +69,7 @@ public class AutoGenerator {
     /**
      * 模板引擎
      */
-    private AbstractTemplateEngine templateEngine = new VelocityTemplateEngine(); // 为了兼容之前逻辑,采用 Velocity 引擎 【 默认 】
+    private AbstractTemplateEngine templateEngine;
 
     /**
      * 生成代码
@@ -88,6 +83,10 @@ public class AutoGenerator {
                 injectionConfig.setConfig(config);
             }
         }
+        if (null == templateEngine) {
+            // 为了兼容之前逻辑,采用 Velocity 引擎 【 默认 】
+            templateEngine = new VelocityTemplateEngine();
+        }
         // 模板引擎初始化执行文件输出
         templateEngine.init(this.pretreatmentConfigBuilder(config)).mkdirs().batchOutput().open();
         logger.debug("==========================文件生成完成!!!==========================");
@@ -121,10 +120,23 @@ public class AutoGenerator {
         return config;
     }
 
+    /**
+     * @return this
+     * @see #getInjectionConfig()
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public InjectionConfig getCfg() {
         return injectionConfig;
     }
 
+    /**
+     * @param injectionConfig injectionConfig
+     * @return this
+     * @see #setInjectionConfig(InjectionConfig)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public AutoGenerator setCfg(InjectionConfig injectionConfig) {
         this.injectionConfig = injectionConfig;
         return this;

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

@@ -220,7 +220,7 @@ public class StrategyConfig {
      */
     @Deprecated
     public boolean containsTablePrefix(String tableName) {
-        return getTablePrefix().stream().anyMatch(tableName::contains);
+        return this.tablePrefix.stream().anyMatch(tableName::contains);
     }
 
     /**
@@ -230,7 +230,7 @@ public class StrategyConfig {
      * @since 3.3.2
      */
     public boolean startsWithTablePrefix(String tableName) {
-        return getTablePrefix().stream().anyMatch(tableName::startsWith);
+        return this.tablePrefix.stream().anyMatch(tableName::startsWith);
     }
 
     public NamingStrategy getColumnNaming() {
@@ -238,7 +238,24 @@ public class StrategyConfig {
         return Optional.ofNullable(columnNaming).orElse(naming);
     }
 
+    /**
+     * @param tablePrefix 表前缀
+     * @return this
+     * @see #addTablePrefix(String...)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public StrategyConfig setTablePrefix(String... tablePrefix) {
+        return addTablePrefix(tablePrefix);
+    }
+
+    /**
+     * 增加表前缀
+     * @since 3.4.1
+     * @param tablePrefix 表前缀
+     * @return this
+     */
+    public StrategyConfig addTablePrefix(String... tablePrefix) {
         this.tablePrefix.addAll(Arrays.asList(tablePrefix));
         return this;
     }
@@ -253,17 +270,71 @@ public class StrategyConfig {
         return this;
     }
 
+    /**
+     * @param include 包含表
+     * @return this
+     * @see #addInclude(String...)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public StrategyConfig setInclude(String... include) {
+        return addInclude(include);
+    }
+
+    /**
+     * 增加包含的表名
+     *
+     * @param include 包含表
+     * @return this
+     * @since 3.4.1
+     */
+    public StrategyConfig addInclude(String... include) {
         this.include.addAll(Arrays.asList(include));
         return this;
     }
 
+    /**
+     * @param exclude 排除表
+     * @return this
+     * @see #addExclude(String...)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public StrategyConfig setExclude(String... exclude) {
+        return addExclude(exclude);
+    }
+
+    /**
+     * 增加排除表
+     *
+     * @param exclude 排除表
+     * @return this
+     * @since 3.4.1
+     */
+    public StrategyConfig addExclude(String... exclude) {
         this.exclude.addAll(Arrays.asList(exclude));
         return this;
     }
 
+    /**
+     * @param fieldPrefixs 字段前缀
+     * @return this
+     * @see #addFieldPrefix(String...)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public StrategyConfig setFieldPrefix(String... fieldPrefixs) {
+        return addFieldPrefix(fieldPrefixs);
+    }
+
+    /**
+     * 增加字段前缀
+     *
+     * @param fieldPrefixs 字段前缀
+     * @return this
+     * @since 3.4.1
+     */
+    public StrategyConfig addFieldPrefix(String... fieldPrefixs) {
         this.fieldPrefix.addAll(Arrays.asList(fieldPrefixs));
         return this;
     }
@@ -355,6 +426,13 @@ public class StrategyConfig {
         return this.addTableFills(tableFillList.toArray(new TableFill[]{}));
     }
 
+    /**
+     * 添加表字段填充
+     *
+     * @param tableFill 填充字段
+     * @return this
+     * @since 3.4.1
+     */
     public StrategyConfig addTableFills(TableFill... tableFill) {
         this.tableFillList.addAll(Arrays.asList(tableFill));
         return this;

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

@@ -16,7 +16,6 @@
 package com.baomidou.mybatisplus.generator.config.builder;
 
 import com.baomidou.mybatisplus.annotation.DbType;
-import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.generator.InjectionConfig;
 import com.baomidou.mybatisplus.generator.config.*;
@@ -99,6 +98,7 @@ public class ConfigBuilder {
      * 表数据查询
      */
     private final DecoratorDbQuery dbQuery;
+
     /**
      * 在构造器中处理配置
      *
@@ -293,26 +293,11 @@ public class ConfigBuilder {
                             isId = StringUtils.isNotBlank(key) && "PRI".equals(key.toUpperCase());
                         }
                     }
-
                     // 处理ID
                     if (isId) {
-                        field.setKeyFlag(true);
+                        field.setKeyFlag(true).setKeyIdentityFlag(dbQuery.isKeyIdentity(results));
                         tableInfo.setHavePrimaryKey(true);
-                        field.setKeyIdentityFlag(dbQuery.isKeyIdentity(results));
-                    } else {
-                        field.setKeyFlag(false);
                     }
-                    // 自定义字段查询
-                    String[] fcs = dbQuery.fieldCustom();
-                    if (null != fcs) {
-                        Map<String, Object> customMap = CollectionUtils.newHashMapWithExpectedSize(fcs.length);
-                        for (String fc : fcs) {
-                            customMap.put(fc, results.getObject(fc));
-                        }
-                        field.setCustomMap(customMap);
-                    }
-                    // 处理其它信息
-                    field.setName(columnName);
                     String newColumnName = columnName;
                     IKeyWordsHandler keyWordsHandler = dataSourceConfig.getKeyWordsHandler();
                     if (keyWordsHandler != null && keyWordsHandler.isKeyWords(columnName)) {
@@ -320,11 +305,13 @@ public class ConfigBuilder {
                         field.setKeyWords(true);
                         newColumnName = keyWordsHandler.formatColumn(columnName);
                     }
-                    field.setColumnName(newColumnName);
-                    field.setType(results.getString(dbQuery.fieldType()));
-                    field.setPropertyName(strategyConfig.getNameConvert().propertyNameConvert(field));
-                    field.setColumnType(dataSourceConfig.getTypeConvert().processTypeConvert(globalConfig, field));
-                    field.setComment(dbQuery.getFiledComment(results));
+                    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()
@@ -342,8 +329,8 @@ public class ConfigBuilder {
         } catch (SQLException e) {
             throw new RuntimeException(e);
         }
-        tableInfo.setFields(fieldList);
-        tableInfo.setCommonFields(commonFieldList);
+        tableInfo.addFields(fieldList);
+        tableInfo.addCommonFields(commonFieldList);
         return tableInfo;
     }
 
@@ -372,7 +359,6 @@ public class ConfigBuilder {
         });
     }
 
-
     /**
      * 不再建议调用此方法,后续不再公开此方法.
      *

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

@@ -88,6 +88,13 @@ public class TableField {
         return this;
     }
 
+    //TODO 先标记一下,后面再考虑。
+    @Deprecated
+    public TableField setPropertyName(String propertyName) {
+        this.propertyName = propertyName;
+        return this;
+    }
+
     public TableField setPropertyName(StrategyConfig strategyConfig, String propertyName) {
         //TODO 这个好像是苗老板写的,有空打死他吧.
         if (strategyConfig.isEntityBooleanColumnRemoveIsPrefix()

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

@@ -16,14 +16,19 @@
 package com.baomidou.mybatisplus.generator.config.po;
 
 import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-import java.util.stream.IntStream;
+import java.util.stream.Collectors;
 
+import com.baomidou.mybatisplus.annotation.FieldFill;
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableLogic;
 import com.baomidou.mybatisplus.annotation.TableName;
-import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
+import com.baomidou.mybatisplus.annotation.Version;
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.generator.config.GlobalConfig;
 import com.baomidou.mybatisplus.generator.config.StrategyConfig;
@@ -52,12 +57,12 @@ public class TableInfo {
     private String serviceName;
     private String serviceImplName;
     private String controllerName;
-    private List<TableField> fields;
+    private final List<TableField> fields = new ArrayList<>();
     private boolean havePrimaryKey;
     /**
      * 公共字段
      */
-    private List<TableField> commonFields;
+    private final List<TableField> commonFields = new ArrayList<>();
     private String fieldNames;
 
     public TableInfo setConvert(boolean convert) {
@@ -96,42 +101,59 @@ public class TableInfo {
         return this;
     }
 
+
+    /**
+     * @see #addFields(List)
+     * @see #addFields(TableField...)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public TableInfo setFields(List<TableField> fields) {
-        this.fields = fields;
-        if (CollectionUtils.isNotEmpty(fields)) {
-            // 收集导入包信息
-            for (TableField field : fields) {
-                if (null != field.getColumnType() && null != field.getColumnType().getPkg()) {
-                    importPackages.add(field.getColumnType().getPkg());
-                }
-                if (field.isKeyFlag()) {
-                    // 主键
-                    if (field.isConvert() || field.isKeyIdentityFlag()) {
-                        importPackages.add(com.baomidou.mybatisplus.annotation.TableId.class.getCanonicalName());
-                    }
-                    // 自增
-                    if (field.isKeyIdentityFlag()) {
-                        importPackages.add(com.baomidou.mybatisplus.annotation.IdType.class.getCanonicalName());
-                    }
-                } else if (field.isConvert()) {
-                    // 普通字段
-                    importPackages.add(com.baomidou.mybatisplus.annotation.TableField.class.getCanonicalName());
-                }
-                if (null != field.getFill()) {
-                    // 填充字段
-                    importPackages.add(com.baomidou.mybatisplus.annotation.TableField.class.getCanonicalName());
-                    importPackages.add(com.baomidou.mybatisplus.annotation.FieldFill.class.getCanonicalName());
-                }
-            }
-        }
+        return addFields(fields);
+    }
+
+    /**
+     * @param fields 字段集合
+     * @return this
+     * @since 3.4.1
+     */
+    public TableInfo addFields(List<TableField> fields) {
+        this.fields.addAll(fields);
         return this;
     }
 
+    /**
+     * @param fields 字段集合
+     * @return this
+     * @since 3.4.1
+     */
+    public TableInfo addFields(TableField... fields) {
+        this.fields.addAll(Arrays.asList(fields));
+        return this;
+    }
+
+    /**
+     * @param pkg 包空间
+     * @return this
+     * @see #addImportPackages(String...)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
     public TableInfo setImportPackages(String pkg) {
         importPackages.add(pkg);
         return this;
     }
 
+    /**
+     * @param pkgs 包空间
+     * @return this
+     * @since 3.4.1
+     */
+    public TableInfo addImportPackages(String... pkgs) {
+        importPackages.addAll(Arrays.asList(pkgs));
+        return this;
+    }
+
     /**
      * 逻辑删除
      */
@@ -139,24 +161,60 @@ public class TableInfo {
         return fields.parallelStream().anyMatch(tf -> tf.getName().equals(logicDeletePropertyName));
     }
 
+    /**
+     * @param fieldNames fieldNames
+     * @deprecated 3.4.1 不打算公开此方法了
+     */
+    @Deprecated
+    public TableInfo setFieldNames(String fieldNames) {
+        this.fieldNames = fieldNames;
+        return this;
+    }
+
     /**
      * 转换filed实体为 xml mapper 中的 base column 字符串信息
      */
     public String getFieldNames() {
-        if (StringUtils.isBlank(fieldNames)
-            && CollectionUtils.isNotEmpty(fields)) {
-            StringBuilder names = new StringBuilder();
-            IntStream.range(0, fields.size()).forEach(i -> {
-                TableField fd = fields.get(i);
-                if (i == fields.size() - 1) {
-                    names.append(fd.getColumnName());
-                } else {
-                    names.append(fd.getColumnName()).append(", ");
-                }
-            });
-            fieldNames = names.toString();
+        //TODO 感觉这个也啥必要,不打算公开set方法了
+        if (StringUtils.isBlank(fieldNames)) {
+            this.fieldNames = this.fields.stream().map(TableField::getColumnName).collect(Collectors.joining(", "));
         }
-        return fieldNames;
+        return this.fieldNames;
+    }
+
+    /**
+     * @param commonFields 公共字段
+     * @return this
+     * @see #addCommonFields(TableField...)
+     * @see #addCommonFields(List)
+     * @deprecated 3.4.1
+     */
+    @Deprecated
+    public TableInfo setCommonFields(List<TableField> commonFields) {
+        return addCommonFields(commonFields);
+    }
+
+    /**
+     * 添加公共字段
+     *
+     * @param commonFields 公共字段
+     * @return this
+     * @since 3.4.1
+     */
+    public TableInfo addCommonFields(TableField... commonFields) {
+        return addCommonFields(Arrays.asList(commonFields));
+    }
+
+    /**
+     * 添加公共字段
+     *
+     * @param commonFields 公共字段
+     * @return this
+     * @since 3.4.1
+     */
+    public TableInfo addCommonFields(List<TableField> commonFields) {
+        this.commonFields.addAll(commonFields);
+        return this;
     }
 
     public void importPackage(StrategyConfig strategyConfig, GlobalConfig globalConfig){
@@ -172,7 +230,7 @@ public class TableInfo {
             }
         }
         if (importSerializable) {
-            this.setImportPackages(Serializable.class.getCanonicalName());
+            this.importPackages.add(Serializable.class.getCanonicalName());
         }
         if (this.isConvert()) {
             this.importPackages.add(TableName.class.getCanonicalName());
@@ -182,16 +240,35 @@ public class TableInfo {
         }
         if (null != globalConfig.getIdType() && this.isHavePrimaryKey()) {
             // 指定需要 IdType 场景
-            this.importPackages.add(com.baomidou.mybatisplus.annotation.IdType.class.getCanonicalName());
-            this.importPackages.add(com.baomidou.mybatisplus.annotation.TableId.class.getCanonicalName());
+            this.importPackages.add(IdType.class.getCanonicalName());
+            this.importPackages.add(TableId.class.getCanonicalName());
         }
-        if (StringUtils.isNotBlank(strategyConfig.getVersionFieldName())
-            && CollectionUtils.isNotEmpty(this.getFields())) {
-            this.getFields().forEach(f -> {
-                if (strategyConfig.getVersionFieldName().equals(f.getName())) {
-                    this.importPackages.add(com.baomidou.mybatisplus.annotation.Version.class.getCanonicalName());
+        this.fields.forEach(field -> {
+            if (null != field.getColumnType() && null != field.getColumnType().getPkg()) {
+                importPackages.add(field.getColumnType().getPkg());
+            }
+            if (field.isKeyFlag()) {
+                // 主键
+                if (field.isConvert() || field.isKeyIdentityFlag()) {
+                    importPackages.add(TableId.class.getCanonicalName());
                 }
-            });
-        }
+                // 自增
+                if (field.isKeyIdentityFlag()) {
+                    importPackages.add(IdType.class.getCanonicalName());
+                }
+            } else if (field.isConvert()) {
+                // 普通字段
+                importPackages.add(TableField.class.getCanonicalName());
+            }
+            if (null != field.getFill()) {
+                // 填充字段
+                importPackages.add(TableField.class.getCanonicalName());
+                importPackages.add(FieldFill.class.getCanonicalName());
+            }
+            String versionFieldName = strategyConfig.getVersionFieldName();
+            if (StringUtils.isNotBlank(versionFieldName) && versionFieldName.equals(field.getName())) {
+                this.importPackages.add(Version.class.getCanonicalName());
+            }
+        });
     }
 }

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

@@ -16,6 +16,7 @@
 package com.baomidou.mybatisplus.generator.config.querys;
 
 import com.baomidou.mybatisplus.annotation.DbType;
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.core.toolkit.StringPool;
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
@@ -23,6 +24,8 @@ import com.baomidou.mybatisplus.generator.config.IDbQuery;
 
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.util.Collections;
+import java.util.Map;
 
 /**
  * 装饰DbQuery
@@ -141,12 +144,17 @@ public class DecoratorDbQuery extends AbstractDbQuery {
         return dbQuery.fieldComment();
     }
 
-    public String getFiledComment(ResultSet resultSet) throws SQLException {
+    public String getFiledComment(ResultSet resultSet) {
         return getResultStringValue(resultSet, this.fieldComment());
     }
 
-    private String getResultStringValue(ResultSet resultSet, String columnLabel) throws SQLException {
-        return StringUtils.isNotBlank(columnLabel) ? StringPool.EMPTY : formatComment(resultSet.getString(columnLabel));
+    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) {
@@ -159,12 +167,34 @@ public class DecoratorDbQuery extends AbstractDbQuery {
     }
 
     @Override
-    public boolean isKeyIdentity(ResultSet results) throws SQLException {
-        return dbQuery.isKeyIdentity(results);
+    public boolean isKeyIdentity(ResultSet results) {
+        try {
+            return dbQuery.isKeyIdentity(results);
+        } catch (SQLException e) {
+            // ignore
+        }
+        return false;
     }
 
     @Override
     public String[] fieldCustom() {
         return dbQuery.fieldCustom();
     }
+
+    public Map<String, Object> getCustomFields(ResultSet resultSet) {
+        String[] fcs = this.fieldCustom();
+        if (null != fcs) {
+            Map<String, Object> customMap = CollectionUtils.newHashMapWithExpectedSize(fcs.length);
+            for (String fc : fcs) {
+                try {
+                    customMap.put(fc, resultSet.getObject(fc));
+                } catch (SQLException sqlException) {
+                    //ignore
+                    customMap.put(fc, null);
+                }
+            }
+            return customMap;
+        }
+        return Collections.emptyMap();
+    }
 }

+ 29 - 0
mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/generator/config/po/TableInfoTest.java

@@ -0,0 +1,29 @@
+package com.baomidou.mybatisplus.generator.config.po;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+
+/**
+ *
+ * @author nieqiurong 2020/9/21.
+ */
+public class TableInfoTest {
+
+    @Test
+    void getFieldNamesTest(){
+        TableInfo tableInfo;
+        tableInfo = new TableInfo();
+        tableInfo.addFields(new TableField().setColumnName("name"));
+        Assertions.assertEquals(tableInfo.getFieldNames(),"name");
+
+        tableInfo = new TableInfo();
+        tableInfo.addFields(new TableField().setColumnName("name"), new TableField().setColumnName("age"));
+        Assertions.assertEquals(tableInfo.getFieldNames(),"name, age");
+
+        tableInfo = new TableInfo();
+        tableInfo.addFields(new TableField().setColumnName("name"), new TableField().setColumnName("age"), new TableField().setColumnName("phone"));
+        Assertions.assertEquals(tableInfo.getFieldNames(),"name, age, phone");
+    }
+
+}