浏览代码

改进优化代码生成器

hubin 7 年之前
父节点
当前提交
1c69ca8063

+ 69 - 68
mybatis-plus-core/src/main/java/com/baomidou/mybatisplus/core/toolkit/StringPool.java

@@ -2,7 +2,7 @@ package com.baomidou.mybatisplus.core.toolkit;
 
 /**
  * Copy to jodd.util
- *
+ * <p>
  * Pool of <code>String</code> constants to prevent repeating of
  * hard-coded <code>String</code> literals in the code.
  * Due to fact that these are <code>public static final</code>
@@ -11,80 +11,81 @@ package com.baomidou.mybatisplus.core.toolkit;
  * There is <b>no</b> performance gain of using this pool.
  * Read: http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.10.5
  * <ul>
- *     <li>Literal strings within the same class in the same package represent references to the same <code>String</code> object.</li>
- *     <li>Literal strings within different classes in the same package represent references to the same <code>String</code> object.</li>
- *     <li>Literal strings within different classes in different packages likewise represent references to the same <code>String</code> object.</li>
- *     <li>Strings computed by constant expressions are computed at compile time and then treated as if they were literals.</li>
- *     <li>Strings computed by concatenation at run time are newly created and therefore distinct.</li>
+ * <li>Literal strings within the same class in the same package represent references to the same <code>String</code> object.</li>
+ * <li>Literal strings within different classes in the same package represent references to the same <code>String</code> object.</li>
+ * <li>Literal strings within different classes in different packages likewise represent references to the same <code>String</code> object.</li>
+ * <li>Strings computed by constant expressions are computed at compile time and then treated as if they were literals.</li>
+ * <li>Strings computed by concatenation at run time are newly created and therefore distinct.</li>
  * </ul>
  */
 public interface StringPool {
 
-    String AMPERSAND        = "&";
-    String AND              = "and";
-    String AT               = "@";
-    String ASTERISK         = "*";
-    String STAR             = ASTERISK;
-    String BACK_SLASH       = "\\";
-    String COLON            = ":";
-    String COMMA            = ",";
-    String DASH             = "-";
-    String DOLLAR           = "$";
-    String DOT              = ".";
-    String DOTDOT           = "..";
-    String DOT_CLASS        = ".class";
-    String DOT_JAVA         = ".java";
-    String EMPTY            = "";
-    String EQUALS           = "=";
-    String FALSE            = "false";
-    String SLASH            = "/";
-    String HASH             = "#";
-    String HAT              = "^";
-    String LEFT_BRACE       = "{";
-    String LEFT_BRACKET     = "(";
-    String LEFT_CHEV        = "<";
-    String NEWLINE          = "\n";
-    String N                = "n";
-    String NO               = "no";
-    String NULL             = "null";
-    String OFF              = "off";
-    String ON               = "on";
-    String PERCENT          = "%";
-    String PIPE             = "|";
-    String PLUS             = "+";
-    String QUESTION_MARK    = "?";
+    String AMPERSAND = "&";
+    String AND = "and";
+    String AT = "@";
+    String ASTERISK = "*";
+    String STAR = ASTERISK;
+    String BACK_SLASH = "\\";
+    String COLON = ":";
+    String COMMA = ",";
+    String DASH = "-";
+    String DOLLAR = "$";
+    String DOT = ".";
+    String DOTDOT = "..";
+    String DOT_CLASS = ".class";
+    String DOT_JAVA = ".java";
+    String DOT_XML = ".xml";
+    String EMPTY = "";
+    String EQUALS = "=";
+    String FALSE = "false";
+    String SLASH = "/";
+    String HASH = "#";
+    String HAT = "^";
+    String LEFT_BRACE = "{";
+    String LEFT_BRACKET = "(";
+    String LEFT_CHEV = "<";
+    String NEWLINE = "\n";
+    String N = "n";
+    String NO = "no";
+    String NULL = "null";
+    String OFF = "off";
+    String ON = "on";
+    String PERCENT = "%";
+    String PIPE = "|";
+    String PLUS = "+";
+    String QUESTION_MARK = "?";
     String EXCLAMATION_MARK = "!";
-    String QUOTE            = "\"";
-    String RETURN           = "\r";
-    String TAB              = "\t";
-    String RIGHT_BRACE      = "}";
-    String RIGHT_BRACKET    = ")";
-    String RIGHT_CHEV       = ">";
-    String SEMICOLON        = ";";
-    String SINGLE_QUOTE     = "'";
-    String BACKTICK         = "`";
-    String SPACE            = " ";
-    String TILDA            = "~";
-    String LEFT_SQ_BRACKET  = "[";
+    String QUOTE = "\"";
+    String RETURN = "\r";
+    String TAB = "\t";
+    String RIGHT_BRACE = "}";
+    String RIGHT_BRACKET = ")";
+    String RIGHT_CHEV = ">";
+    String SEMICOLON = ";";
+    String SINGLE_QUOTE = "'";
+    String BACKTICK = "`";
+    String SPACE = " ";
+    String TILDA = "~";
+    String LEFT_SQ_BRACKET = "[";
     String RIGHT_SQ_BRACKET = "]";
-    String TRUE             = "true";
-    String UNDERSCORE       = "_";
-    String UTF_8            = "UTF-8";
-    String US_ASCII			= "US-ASCII";
-    String ISO_8859_1       = "ISO-8859-1";
-    String Y                = "y";
-    String YES              = "yes";
-    String ONE 				= "1";
-    String ZERO				= "0";
-    String DOLLAR_LEFT_BRACE= "${";
-    String HASH_LEFT_BRACE  = "#{";
-    String CRLF				= "\r\n";
+    String TRUE = "true";
+    String UNDERSCORE = "_";
+    String UTF_8 = "UTF-8";
+    String US_ASCII = "US-ASCII";
+    String ISO_8859_1 = "ISO-8859-1";
+    String Y = "y";
+    String YES = "yes";
+    String ONE = "1";
+    String ZERO = "0";
+    String DOLLAR_LEFT_BRACE = "${";
+    String HASH_LEFT_BRACE = "#{";
+    String CRLF = "\r\n";
 
-    String HTML_NBSP		= "&nbsp;";
-    String HTML_AMP			= "&amp";
-    String HTML_QUOTE 		= "&quot;";
-    String HTML_LT 			= "&lt;";
-    String HTML_GT 			= "&gt;";
+    String HTML_NBSP = "&nbsp;";
+    String HTML_AMP = "&amp";
+    String HTML_QUOTE = "&quot;";
+    String HTML_LT = "&lt;";
+    String HTML_GT = "&gt;";
 
     // ---------------------------------------------------------------- array
 

+ 22 - 3
mybatis-plus-extension/src/main/java/com/baomidou/mybatisplus/extension/toolkit/PackageHelper.java

@@ -15,7 +15,10 @@
  */
 package com.baomidou.mybatisplus.extension.toolkit;
 
-import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
+import java.io.File;
+import java.util.HashSet;
+import java.util.Set;
+
 import org.springframework.core.io.Resource;
 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 import org.springframework.core.io.support.ResourcePatternResolver;
@@ -23,8 +26,8 @@ import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
 import org.springframework.core.type.classreading.MetadataReader;
 import org.springframework.core.type.classreading.MetadataReaderFactory;
 import org.springframework.util.ClassUtils;
-import java.util.HashSet;
-import java.util.Set;
+
+import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
 
 /**
  * <p>
@@ -112,4 +115,20 @@ public class PackageHelper {
             throw ExceptionUtils.mpe("not find scanTypePackage:" + pkg, e);
         }
     }
+
+    /**
+     * <p>
+     * 新建文件目录
+     * </p>
+     *
+     * @param file 文件
+     */
+    public static void mkDir(File file) {
+        if (file.getParentFile().exists()) {
+            file.mkdir();
+        } else {
+            mkDir(file.getParentFile());
+            file.mkdir();
+        }
+    }
 }

+ 18 - 0
mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/config/FileOutConfig.java

@@ -15,6 +15,9 @@
  */
 package com.baomidou.mybatisplus.generator.config;
 
+import java.io.File;
+
+import com.baomidou.mybatisplus.extension.toolkit.PackageHelper;
 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
 
 import lombok.Data;
@@ -49,4 +52,19 @@ public abstract class FileOutConfig {
      * 输出文件
      */
     public abstract String outputFile(TableInfo tableInfo);
+
+    /**
+     * <p>
+     * 检查文件目录,不存在自动递归创建
+     * </p>
+     *
+     * @param filePath 文件路径
+     */
+    public void checkDir(String filePath) {
+        File file = new File(filePath);
+        boolean exist = file.exists();
+        if (!exist) {
+            PackageHelper.mkDir(file.getParentFile());
+        }
+    }
 }

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

@@ -31,11 +31,6 @@ import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  */
 public class StrategyConfig {
 
-    /**
-     * 表名、字段名、是否使用下划线命名(默认 false)
-     */
-    private boolean dbColumnUnderline = false;
-
     /**
      * 是否大写命名
      */
@@ -164,15 +159,6 @@ public class StrategyConfig {
      */
     private List<TableFill> tableFillList = null;
 
-    public boolean isDbColumnUnderline() {
-        return dbColumnUnderline;
-    }
-
-    public StrategyConfig setDbColumnUnderline(boolean dbColumnUnderline) {
-        this.dbColumnUnderline = dbColumnUnderline;
-        return this;
-    }
-
     /**
      * <p>
      * 大写命名、字段符合大写字母数字下划线命名

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

@@ -15,13 +15,14 @@
  */
 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;
+import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 import com.baomidou.mybatisplus.generator.config.rules.PropertyInfo;
 
-import java.util.Map;
-
 /**
  * <p>
  * 表字段信息
@@ -62,7 +63,7 @@ public class TableField {
             this.convert = false;
         } else {
             // 转换字段
-            if (strategyConfig.isDbColumnUnderline()) {
+            if (NamingStrategy.underline_to_camel == strategyConfig.getColumnNaming()) {
                 // 包含大写处理
                 if (StringUtils.containsUpperCase(name)) {
                     this.convert = true;

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

@@ -23,6 +23,7 @@ import java.util.stream.IntStream;
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.core.toolkit.StringUtils;
 import com.baomidou.mybatisplus.generator.config.StrategyConfig;
+import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 
 /**
  * <p>
@@ -64,7 +65,7 @@ public class TableInfo {
             this.convert = false;
         } else {
             // 转换字段
-            if (strategyConfig.isDbColumnUnderline()) {
+            if (NamingStrategy.underline_to_camel == strategyConfig.getColumnNaming()) {
                 // 包含大写处理
                 if (StringUtils.containsUpperCase(name)) {
                     this.convert = true;

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

@@ -29,14 +29,15 @@ import org.slf4j.LoggerFactory;
 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.extension.toolkit.PackageHelper;
 import com.baomidou.mybatisplus.generator.InjectionConfig;
 import com.baomidou.mybatisplus.generator.config.ConstVal;
 import com.baomidou.mybatisplus.generator.config.FileOutConfig;
 import com.baomidou.mybatisplus.generator.config.GlobalConfig;
 import com.baomidou.mybatisplus.generator.config.TemplateConfig;
 import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
-import com.baomidou.mybatisplus.generator.config.rules.FileType;
 import com.baomidou.mybatisplus.generator.config.po.TableInfo;
+import com.baomidou.mybatisplus.generator.config.rules.FileType;
 
 
 /**
@@ -291,20 +292,11 @@ public abstract class AbstractTemplateEngine {
         File file = new File(filePath);
         boolean exist = file.exists();
         if (!exist) {
-            mkDir(file.getParentFile());
+            PackageHelper.mkDir(file.getParentFile());
         }
         return !exist || getConfigBuilder().getGlobalConfig().isFileOverride();
     }
 
-    protected void mkDir(File file) {
-        if (file.getParentFile().exists()) {
-            file.mkdir();
-        } else {
-            mkDir(file.getParentFile());
-            file.mkdir();
-        }
-    }
-
     /**
      * 文件后缀
      */

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

@@ -87,8 +87,9 @@ public class CodeGeneratorTest {
         strategyConfig
             .setCapitalMode(true)
             .setEntityLombokModel(false)
-            .setDbColumnUnderline(true)
+            // .setDbColumnUnderline(true) 改为如下 2 个配置
             .setNaming(NamingStrategy.underline_to_camel)
+            .setColumnNaming(NamingStrategy.underline_to_camel)
             .entityTableFieldAnnotationEnable(enableTableFieldAnnotation)
             .fieldPrefix(fieldPrefix)//test_id -> id, test_type -> type
             .setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组

+ 30 - 29
mybatis-plus-generator/src/test/java/com/baomidou/mybatisplus/test/generator/DB2Generator.java

@@ -10,49 +10,50 @@ import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
 
 public class DB2Generator {
 
-	public static void main(String[] args) {
-		String packageName = "com.crea.gwms";
+    public static void main(String[] args) {
+        String packageName = "com.crea.gwms";
         boolean serviceNameStartWithI = true;//user -> UserService, 设置成true: user -> IUserService
         generateByTables(serviceNameStartWithI, packageName, "USER");
-	}
+    }
 
-	public static void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
+    public static void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) {
         GlobalConfig config = new GlobalConfig();
         String dbUrl = "jdbc:db2://192.168.0.227:50000/TRADECTR";
         DataSourceConfig dataSourceConfig = new DataSourceConfig();
         dataSourceConfig.setDbType(DbType.DB2)
-                .setUrl(dbUrl)
-                .setUsername("tc")
-                .setPassword("business")
-                .setDriverName("com.ibm.db2.jcc.DB2Driver");
+            .setUrl(dbUrl)
+            .setUsername("tc")
+            .setPassword("business")
+            .setDriverName("com.ibm.db2.jcc.DB2Driver");
         StrategyConfig strategyConfig = new StrategyConfig();
         strategyConfig
-                .setCapitalMode(true)
-                .setEntityLombokModel(false)
-                .setDbColumnUnderline(true)
-                .setNaming(NamingStrategy.underline_to_camel)
-                .entityTableFieldAnnotationEnable(true)//实体属性上添加表字段映射
-                .setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
+            .setCapitalMode(true)
+            .setEntityLombokModel(false)
+            // .setDbColumnUnderline(true) 改为如下 2 个配置
+            .setNaming(NamingStrategy.underline_to_camel)
+            .setColumnNaming(NamingStrategy.underline_to_camel)
+            .entityTableFieldAnnotationEnable(true)//实体属性上添加表字段映射
+            .setInclude(tableNames);//修改替换成你需要的表名,多个表名传数组
         config.setActiveRecord(true)
-                .setEnableCache(false)// XML 二级缓存
-                .setAuthor("zhanyao")
-                .setBaseResultMap(true)// XML ResultMap
-                .setBaseColumnList(false)// XML columList
-                .setOutputDir("/Users/zhanyao/Downloads/code")
-                .setFileOverride(true);
+            .setEnableCache(false)// XML 二级缓存
+            .setAuthor("zhanyao")
+            .setBaseResultMap(true)// XML ResultMap
+            .setBaseColumnList(false)// XML columList
+            .setOutputDir("/Users/zhanyao/Downloads/code")
+            .setFileOverride(true);
         if (!serviceNameStartWithI) {
             config.setServiceName("%sService");
         }
         new AutoGenerator().setGlobalConfig(config)
-                .setDataSource(dataSourceConfig)
-                .setStrategy(strategyConfig)
-                .setPackageInfo(
-                        new PackageConfig()
-                                .setParent(packageName)
-                                .setController("controller")
-                                .setMapper("dao")
-                                .setEntity("bean")
-                ).execute();
+            .setDataSource(dataSourceConfig)
+            .setStrategy(strategyConfig)
+            .setPackageInfo(
+                new PackageConfig()
+                    .setParent(packageName)
+                    .setController("controller")
+                    .setMapper("dao")
+                    .setEntity("bean")
+            ).execute();
     }
 
     private void generateByTables(String packageName, String... tableNames) {