From e0614069bef23695be7ce1410da3c024ade7205d Mon Sep 17 00:00:00 2001 From: hewei Date: Mon, 28 May 2018 14:37:54 +0800 Subject: [PATCH] =?UTF-8?q?TableConfigurationPlugin=20=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../plugins/TableConfigurationPlugin.java | 81 ++++++++++++++--- .../plugins/TableConfigurationPluginTest.java | 87 +++++++++++++++++-- ...atis-generator-with-columnRenamingRule.xml | 57 ++++++++++++ ...enerator-with-domainObjectRenamingRule.xml | 56 ++++++++++++ 4 files changed, 262 insertions(+), 19 deletions(-) create mode 100644 src/test/resources/scripts/TableConfigurationPlugin/mybatis-generator-with-columnRenamingRule.xml create mode 100644 src/test/resources/scripts/TableConfigurationPlugin/mybatis-generator-with-domainObjectRenamingRule.xml diff --git a/src/main/java/com/itfsw/mybatis/generator/plugins/TableConfigurationPlugin.java b/src/main/java/com/itfsw/mybatis/generator/plugins/TableConfigurationPlugin.java index 1ef04bd..6a2cae1 100644 --- a/src/main/java/com/itfsw/mybatis/generator/plugins/TableConfigurationPlugin.java +++ b/src/main/java/com/itfsw/mybatis/generator/plugins/TableConfigurationPlugin.java @@ -20,14 +20,22 @@ import com.itfsw.mybatis.generator.plugins.utils.BasePlugin; import com.itfsw.mybatis.generator.plugins.utils.BeanUtils; import com.itfsw.mybatis.generator.plugins.utils.hook.ITableConfigurationHook; import org.mybatis.generator.api.FullyQualifiedTable; +import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.config.ColumnRenamingRule; import org.mybatis.generator.config.DomainObjectRenamingRule; +import org.mybatis.generator.config.PropertyRegistry; import org.mybatis.generator.config.TableConfiguration; +import org.mybatis.generator.internal.util.StringUtility; import java.util.List; import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import static org.mybatis.generator.internal.util.JavaBeansUtil.getCamelCaseString; +import static org.mybatis.generator.internal.util.JavaBeansUtil.getValidPropertyName; +import static org.mybatis.generator.internal.util.StringUtility.isTrue; import static org.mybatis.generator.internal.util.StringUtility.stringHasValue; /** @@ -41,8 +49,10 @@ import static org.mybatis.generator.internal.util.StringUtility.stringHasValue; public class TableConfigurationPlugin extends BasePlugin implements ITableConfigurationHook { public static final String PRO_TABLE_SEARCH_STRING = "domainObjectRenamingRule.searchString"; // 查找 property public static final String PRO_TABLE_REPLACE_STRING = "domainObjectRenamingRule.replaceString"; // 替换 property + public static final String PRO_TABLE_REPLACE_DISABLE = "domainObjectRenamingRule.disable"; // 替换 property public static final String PRO_COLUMN_SEARCH_STRING = "columnRenamingRule.searchString"; // 查找 property public static final String PRO_COLUMN_REPLACE_STRING = "columnRenamingRule.replaceString"; // 替换 property + public static final String PRO_COLUMN_REPLACE_DISABLE = "columnRenamingRule.disable"; // 替换 property public static final String PRO_CLIENT_SUFFIX = "clientSuffix"; // client 结尾 public static final String PRO_SQL_MAP_SUFFIX = "sqlMapSuffix"; // sqlMap 结尾 @@ -51,8 +61,11 @@ public class TableConfigurationPlugin extends BasePlugin implements ITableConfig private String tableSearchString; private String tableReplaceString; + private boolean tableReplaceDisable; private String columnSearchString; private String columnReplaceString; + private boolean columnReplaceDisable; + private String clientSuffix; // client 结尾 private String sqlMapSuffix; // sqlMap 结尾 @@ -67,19 +80,12 @@ public class TableConfigurationPlugin extends BasePlugin implements ITableConfig @Override public boolean validate(List warnings) { Properties properties = this.getProperties(); - // 如果配置了searchString 或者 replaceString,二者不允许单独存在 - if ((properties.getProperty(PRO_TABLE_SEARCH_STRING) == null && properties.getProperty(PRO_TABLE_REPLACE_STRING) != null) - || (properties.getProperty(PRO_TABLE_SEARCH_STRING) != null && properties.getProperty(PRO_TABLE_REPLACE_STRING) == null) - || (properties.getProperty(PRO_COLUMN_SEARCH_STRING) == null && properties.getProperty(PRO_COLUMN_REPLACE_STRING) != null) - || (properties.getProperty(PRO_COLUMN_SEARCH_STRING) != null && properties.getProperty(PRO_COLUMN_REPLACE_STRING) == null)) { - warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件的searchString、replaceString属性需配合使用,不能单独存在!"); - return false; - } this.tableSearchString = properties.getProperty(PRO_TABLE_SEARCH_STRING); this.tableReplaceString = properties.getProperty(PRO_TABLE_REPLACE_STRING); this.columnSearchString = properties.getProperty(PRO_COLUMN_SEARCH_STRING); - this.columnReplaceString = properties.getProperty(PRO_COLUMN_REPLACE_STRING); + this.columnReplaceString = properties.getProperty(PRO_COLUMN_REPLACE_STRING); // 和官方行为保持一致 + this.exampleSuffix = properties.getProperty(PRO_EXAMPLE_SUFFIX); this.clientSuffix = properties.getProperty(PRO_CLIENT_SUFFIX); this.sqlMapSuffix = properties.getProperty(PRO_SQL_MAP_SUFFIX); @@ -98,24 +104,38 @@ public class TableConfigurationPlugin extends BasePlugin implements ITableConfig TableConfiguration tableConfiguration = introspectedTable.getTableConfiguration(); FullyQualifiedTable fullyQualifiedTable = introspectedTable.getFullyQualifiedTable(); + String tableReplaceDisable = tableConfiguration.getProperty(PRO_TABLE_REPLACE_DISABLE); + this.tableReplaceDisable = tableReplaceDisable == null ? false : StringUtility.isTrue(tableReplaceDisable); + String columnReplaceDisable = tableConfiguration.getProperty(PRO_COLUMN_REPLACE_DISABLE); + this.columnReplaceDisable = columnReplaceDisable == null ? false : StringUtility.isTrue(columnReplaceDisable); + String javaClientInterfacePackage = (String) BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateJavaClientInterfacePackage"); String sqlMapPackage = (String) BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateSqlMapPackage"); String javaModelPackage = (String) BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateJavaModelPackage"); // --------------------- table 重命名 ---------------------------- if (tableConfiguration.getDomainObjectRenamingRule() == null - && this.tableSearchString != null && this.tableReplaceString != null) { + && this.tableSearchString != null && !this.tableReplaceDisable) { DomainObjectRenamingRule rule = new DomainObjectRenamingRule(); rule.setSearchString(this.tableSearchString); rule.setReplaceString(this.tableReplaceString); tableConfiguration.setDomainObjectRenamingRule(rule); + BeanUtils.setProperty(introspectedTable.getFullyQualifiedTable(), "domainObjectRenamingRule", rule); + + // 重新初始化一下属性 + BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateJavaClientAttributes"); + BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateModelAttributes"); + BeanUtils.invoke(introspectedTable, IntrospectedTable.class, "calculateXmlAttributes"); } // --------------------- column 重命名 --------------------------- if (tableConfiguration.getColumnRenamingRule() == null - && this.columnSearchString != null && this.columnReplaceString != null) { + && this.columnSearchString != null && !this.columnReplaceDisable) { ColumnRenamingRule rule = new ColumnRenamingRule(); rule.setSearchString(this.columnSearchString); rule.setReplaceString(this.columnReplaceString); tableConfiguration.setColumnRenamingRule(rule); + + // introspectedTable 使用到的所有column过滤并替换 + this.renameColumns(introspectedTable.getAllColumns(), rule, tableConfiguration); } // ---------------------- 后缀修正 ------------------------------- @@ -159,8 +179,7 @@ public class TableConfigurationPlugin extends BasePlugin implements ITableConfig introspectedTable.setMyBatis3XmlMapperFileName(sb.toString()); } - - // 2. example + // 3. example if (this.exampleSuffix != null) { StringBuilder sb = new StringBuilder(); sb.append(javaModelPackage); @@ -169,7 +188,7 @@ public class TableConfigurationPlugin extends BasePlugin implements ITableConfig sb.append(this.exampleSuffix); introspectedTable.setExampleType(sb.toString()); } - // 3. model + // 4. model if (this.modelSuffix != null) { StringBuilder sb = new StringBuilder(); sb.append(javaModelPackage); @@ -198,4 +217,38 @@ public class TableConfigurationPlugin extends BasePlugin implements ITableConfig e.printStackTrace(); } } + + /** + * column rename + * @param columns + * @param rule + * @param tc + */ + private void renameColumns(List columns, ColumnRenamingRule rule, TableConfiguration tc) { + Pattern pattern = Pattern.compile(rule.getSearchString()); + String replaceString = rule.getReplaceString(); + replaceString = replaceString == null ? "" : replaceString; + + for (IntrospectedColumn introspectedColumn : columns) { + String calculatedColumnName; + if (pattern == null) { + calculatedColumnName = introspectedColumn.getActualColumnName(); + } else { + Matcher matcher = pattern.matcher(introspectedColumn.getActualColumnName()); + calculatedColumnName = matcher.replaceAll(replaceString); + } + + if (isTrue(tc.getProperty(PropertyRegistry.TABLE_USE_ACTUAL_COLUMN_NAMES))) { + introspectedColumn.setJavaProperty(getValidPropertyName(calculatedColumnName)); + } else if (isTrue(tc.getProperty(PropertyRegistry.TABLE_USE_COMPOUND_PROPERTY_NAMES))) { + StringBuilder sb = new StringBuilder(); + sb.append(calculatedColumnName); + sb.append('_'); + sb.append(getCamelCaseString(introspectedColumn.getRemarks(), true)); + introspectedColumn.setJavaProperty(getValidPropertyName(sb.toString())); + } else { + introspectedColumn.setJavaProperty(getCamelCaseString(calculatedColumnName, false)); + } + } + } } diff --git a/src/test/java/com/itfsw/mybatis/generator/plugins/TableConfigurationPluginTest.java b/src/test/java/com/itfsw/mybatis/generator/plugins/TableConfigurationPluginTest.java index 2473790..1c0c003 100644 --- a/src/test/java/com/itfsw/mybatis/generator/plugins/TableConfigurationPluginTest.java +++ b/src/test/java/com/itfsw/mybatis/generator/plugins/TableConfigurationPluginTest.java @@ -16,12 +16,17 @@ package com.itfsw.mybatis.generator.plugins; -import com.itfsw.mybatis.generator.plugins.tools.AbstractShellCallback; -import com.itfsw.mybatis.generator.plugins.tools.DBHelper; -import com.itfsw.mybatis.generator.plugins.tools.MyBatisGeneratorTool; +import com.itfsw.mybatis.generator.plugins.tools.*; import org.apache.ibatis.session.SqlSession; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; +import org.mybatis.generator.api.GeneratedJavaFile; +import org.mybatis.generator.api.MyBatisGenerator; +import org.mybatis.generator.api.dom.java.Field; +import org.mybatis.generator.api.dom.java.TopLevelClass; + +import java.util.List; /** * --------------------------------------------------------------------------- @@ -37,13 +42,85 @@ public class TableConfigurationPluginTest { DBHelper.createDB("scripts/TableConfigurationPlugin/init.sql"); } + /** + * 测试domainObjectRenamingRule + */ @Test - public void test() throws Exception { - MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/TableConfigurationPlugin/mybatis-generator.xml"); + public void testDomainObjectRenamingRule() throws Exception { + // 规则 ^T 替换成 Test + MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/TableConfigurationPlugin/mybatis-generator-with-domainObjectRenamingRule.xml"); + MyBatisGenerator myBatisGenerator = tool.generate(); + for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()){ + String name = file.getCompilationUnit().getType().getShortName(); + Assert.assertTrue(name.matches("Testb.*")); + } + // 执行一条语句确认其可用 tool.generate(() -> DBHelper.resetDB("scripts/TableConfigurationPlugin/init.sql"), new AbstractShellCallback() { @Override public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { + ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TestbMapper"))); + ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TestbExample"); + ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria")); + criteria.invoke("andIdLessThan", 4L); + + // sql + String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "selectByExample", tbExample.getObject()); + Assert.assertEquals(sql, "select id, field1, inc_f1, inc_f2, inc_f3 from tb WHERE ( id < '4' )"); + // 执行 + List list = (List) tbMapper.invoke("selectByExample", tbExample.getObject()); + Assert.assertEquals(list.size(), 3); + } + }); + } + + /** + * 测试columnRenamingRule + */ + @Test + public void testColumnRenamingRule() throws Exception { + // 规则 ^T 替换成 Test + MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/TableConfigurationPlugin/mybatis-generator-with-columnRenamingRule.xml"); + MyBatisGenerator myBatisGenerator = tool.generate(); + for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()){ + if (file.getFileName().equals("Tb.java")){ + int count = 0; + for (Field field : ((TopLevelClass)(file.getCompilationUnit())).getFields()){ + if (field.getName().startsWith("increment")){ + count++; + } + } + Assert.assertEquals(count, 3); + } + } + + // 执行一条语句确认其可用 + tool.generate(() -> DBHelper.resetDB("scripts/TableConfigurationPlugin/init.sql"), new AbstractShellCallback() { + @Override + public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { + ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); + + ObjectUtil tbExample = new ObjectUtil(loader, packagz + ".TbExample"); + ObjectUtil criteria = new ObjectUtil(tbExample.invoke("createCriteria")); + criteria.invoke("andIdEqualTo", 4L); + + ObjectUtil tb = new ObjectUtil(loader, packagz + ".Tb"); + tb.set("id", 4L); + tb.set("field1", "ts1"); + tb.set("incrementF1", 5L); + + // sql + String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExample", tb.getObject(), tbExample.getObject()); + Assert.assertEquals(sql, "update tb set id = 4, field1 = 'ts1', inc_f1 = 5, inc_f2 = null, inc_f3 = null WHERE ( id = '4' )"); + // 执行 + int count = (int) tbMapper.invoke("updateByExample", tb.getObject(), tbExample.getObject()); + Assert.assertEquals(count, 1); + // 执行结果查询 + List list = (List) tbMapper.invoke("selectByExample", tbExample.getObject()); + ObjectUtil result = new ObjectUtil(list.get(0)); + Assert.assertEquals(result.get("id"), 4L); + Assert.assertEquals(result.get("field1"), "ts1"); + Assert.assertEquals(result.get("incrementF1"), 5L); } }); } diff --git a/src/test/resources/scripts/TableConfigurationPlugin/mybatis-generator-with-columnRenamingRule.xml b/src/test/resources/scripts/TableConfigurationPlugin/mybatis-generator-with-columnRenamingRule.xml new file mode 100644 index 0000000..779ae36 --- /dev/null +++ b/src/test/resources/scripts/TableConfigurationPlugin/mybatis-generator-with-columnRenamingRule.xml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + \ No newline at end of file diff --git a/src/test/resources/scripts/TableConfigurationPlugin/mybatis-generator-with-domainObjectRenamingRule.xml b/src/test/resources/scripts/TableConfigurationPlugin/mybatis-generator-with-domainObjectRenamingRule.xml new file mode 100644 index 0000000..bba83b8 --- /dev/null +++ b/src/test/resources/scripts/TableConfigurationPlugin/mybatis-generator-with-domainObjectRenamingRule.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+
\ No newline at end of file