Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
218250e9eb | ||
|
|
bd656b8d3b | ||
|
|
706fad7eb1 | ||
|
|
e6f607d37c | ||
|
|
d70d056ef1 | ||
|
|
84dcfc69ac |
+1
-1
@@ -12,4 +12,4 @@
|
||||
hs_err_pid*
|
||||
.idea/
|
||||
mybatis-generator-plugin.iml
|
||||
target/
|
||||
target/
|
||||
|
||||
@@ -26,7 +26,7 @@ Maven引用:
|
||||
<dependency>
|
||||
<groupId>com.itfsw</groupId>
|
||||
<artifactId>mybatis-generator-plugin</artifactId>
|
||||
<version>1.0.13</version>
|
||||
<version>1.0.14</version>
|
||||
</dependency>
|
||||
```
|
||||
---------------------------------------
|
||||
@@ -983,7 +983,7 @@ Mybatis Generator是原生支持自定义注释的(commentGenerator配置type
|
||||
]]></comment>
|
||||
</template>
|
||||
```
|
||||
### 13. 增量插件
|
||||
### 14. 增量插件
|
||||
为更新操作生成set filedxxx = filedxxx +/- inc 操作,方便某些统计字段的更新操作,常用于某些需要计数的场景;
|
||||
|
||||
插件:
|
||||
@@ -1015,7 +1015,7 @@ public class Test {
|
||||
}
|
||||
}
|
||||
```
|
||||
### 13. 查询结果选择性返回插件
|
||||
### 15. 查询结果选择性返回插件
|
||||
一般我们在做查询优化的时候会要求查询返回时不要返回自己不需要的字段数据,因为Sending data所花费的时间和加大内存的占用
|
||||
,所以我们看到官方对于大数据的字段会拆分成xxxWithBLOBs的操作,但是这种拆分还是不能精确到具体列返回。
|
||||
所以该插件的作用就是精确指定查询操作所需要返回的字段信息,实现查询的精确返回。
|
||||
@@ -1043,4 +1043,4 @@ public class Test {
|
||||
// 同理还有 selectByPrimaryKeySelective,selectOneByExampleSelective(SelectOneByExamplePlugin插件配合使用)方法
|
||||
}
|
||||
}
|
||||
```
|
||||
```
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
<groupId>com.itfsw</groupId>
|
||||
<artifactId>mybatis-generator-plugin</artifactId>
|
||||
<version>1.0.13</version>
|
||||
<version>1.0.14</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>${project.groupId}:${project.artifactId}</name>
|
||||
@@ -212,7 +212,7 @@
|
||||
<connection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</connection>
|
||||
<developerConnection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</developerConnection>
|
||||
<url>https://github.com/itfsw/mybatis-generator-plugin</url>
|
||||
<tag>V1.0.13</tag>
|
||||
<tag>V1.0.14</tag>
|
||||
</scm>
|
||||
|
||||
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++distribution++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
|
||||
|
||||
@@ -40,6 +40,8 @@ import java.util.List;
|
||||
*/
|
||||
public class IncrementsPlugin extends BasePlugin {
|
||||
public static final String PRE_INCREMENTS_COLUMNS = "incrementsColumns"; // incrementsColumns property
|
||||
public static final String FIELD_INC_MAP = "incrementsColumnsInfoMap"; // 为了防止和用户数据库字段冲突,特殊命名
|
||||
public static final String METHOD_INC_CHECK = "hasIncsForColumn"; // inc 检查方法名称
|
||||
private IncrementsPluginTools incTools; // 增量插件工具
|
||||
|
||||
/**
|
||||
|
||||
@@ -154,7 +154,6 @@ public class ModelBuilderPlugin extends BasePlugin {
|
||||
mInc.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "value"));
|
||||
commentGenerator.addGeneralMethodComment(mInc, introspectedTable);
|
||||
eIncrements.addMethod(mInc);
|
||||
logger.debug("itfsw(数据Model属性对应Column获取插件):" + topLevelClass.getType().getShortName() + ".Column增加构造方法和column属性。");
|
||||
|
||||
Method mValue = JavaElementGeneratorTools.generateGetterMethod(fValue);
|
||||
commentGenerator.addGeneralMethodComment(mValue, introspectedTable);
|
||||
@@ -163,7 +162,7 @@ public class ModelBuilderPlugin extends BasePlugin {
|
||||
innerClass.addInnerEnum(eIncrements);
|
||||
// 增加field
|
||||
Field fIncrements = JavaElementGeneratorTools.generateField(
|
||||
"incs",
|
||||
IncrementsPlugin.FIELD_INC_MAP,
|
||||
JavaVisibility.PROTECTED,
|
||||
new FullyQualifiedJavaType("Map<String, " + incTools.getIncEnum().getFullyQualifiedName() + ">"),
|
||||
"new HashMap<String, " + incTools.getIncEnum().getFullyQualifiedName() + ">()"
|
||||
@@ -179,6 +178,16 @@ public class ModelBuilderPlugin extends BasePlugin {
|
||||
Method mSetter = JavaElementGeneratorTools.generateSetterMethod(fIncrements);
|
||||
commentGenerator.addSetterComment(mSetter, introspectedTable, null);
|
||||
topLevelClass.addMethod(mSetter);
|
||||
// 增加判断方法
|
||||
Method mHasIncsForColumn = JavaElementGeneratorTools.generateMethod(
|
||||
IncrementsPlugin.METHOD_INC_CHECK,
|
||||
JavaVisibility.PUBLIC,
|
||||
FullyQualifiedJavaType.getBooleanPrimitiveInstance(),
|
||||
new Parameter(FullyQualifiedJavaType.getStringInstance(), "column")
|
||||
);
|
||||
commentGenerator.addGeneralMethodComment(mHasIncsForColumn, introspectedTable);
|
||||
mHasIncsForColumn.addBodyLine("return " + IncrementsPlugin.FIELD_INC_MAP + ".get(column) != null;");
|
||||
FormatTools.addMethodWithBestPosition(topLevelClass, mHasIncsForColumn);
|
||||
}
|
||||
|
||||
// Builder 中 添加字段支持
|
||||
@@ -196,7 +205,7 @@ public class ModelBuilderPlugin extends BasePlugin {
|
||||
commentGenerator.addSetterComment(mIncrements, introspectedTable, column);
|
||||
|
||||
Method setterMethod = JavaBeansUtil.getJavaBeansSetter(column, context, introspectedTable);
|
||||
mIncrements.addBodyLine("obj.incs.put(\"" + column.getActualColumnName() + "\", inc);");
|
||||
mIncrements.addBodyLine("obj." + IncrementsPlugin.FIELD_INC_MAP + ".put(\"" + column.getActualColumnName() + "\", inc);");
|
||||
mIncrements.addBodyLine("obj." + setterMethod.getName() + "(" + field.getName() + ");");
|
||||
mIncrements.addBodyLine("return this;");
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ package com.itfsw.mybatis.generator.plugins.utils;
|
||||
import org.mybatis.generator.api.dom.java.InnerClass;
|
||||
import org.mybatis.generator.api.dom.java.Interface;
|
||||
import org.mybatis.generator.api.dom.java.Method;
|
||||
import org.mybatis.generator.api.dom.java.TopLevelClass;
|
||||
import org.mybatis.generator.api.dom.xml.Attribute;
|
||||
import org.mybatis.generator.api.dom.xml.Element;
|
||||
import org.mybatis.generator.api.dom.xml.XmlElement;
|
||||
@@ -41,30 +42,7 @@ public class FormatTools {
|
||||
* @param method
|
||||
*/
|
||||
public static void addMethodWithBestPosition(InnerClass innerClass, Method method){
|
||||
List<Method> methods = innerClass.getMethods();
|
||||
int index = -1;
|
||||
for (int i = 0; i < methods.size(); i++){
|
||||
Method m = methods.get(i);
|
||||
if (m.getName().equals(method.getName())){
|
||||
if (m.getParameters().size() <= method.getParameters().size()){
|
||||
index = i + 1;
|
||||
} else {
|
||||
index = i;
|
||||
}
|
||||
} else if (m.getName().startsWith(method.getName())){
|
||||
if (index == - 1){
|
||||
index = i;
|
||||
}
|
||||
} else if (method.getName().startsWith(m.getName())){
|
||||
index = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (index == -1 || index >= methods.size()){
|
||||
innerClass.addMethod(method);
|
||||
} else {
|
||||
methods.add(index, method);
|
||||
}
|
||||
addMethodWithBestPosition(method, innerClass.getMethods());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -74,30 +52,17 @@ public class FormatTools {
|
||||
* @param method
|
||||
*/
|
||||
public static void addMethodWithBestPosition(Interface interfacz, Method method){
|
||||
List<Method> methods = interfacz.getMethods();
|
||||
int index = -1;
|
||||
for (int i = 0; i < methods.size(); i++){
|
||||
Method m = methods.get(i);
|
||||
if (m.getName().equals(method.getName())){
|
||||
if (m.getParameters().size() <= method.getParameters().size()){
|
||||
index = i + 1;
|
||||
} else {
|
||||
index = i;
|
||||
}
|
||||
} else if (m.getName().startsWith(method.getName())){
|
||||
if (index == - 1){
|
||||
index = i;
|
||||
}
|
||||
} else if (method.getName().startsWith(m.getName())){
|
||||
index = i + 1;
|
||||
}
|
||||
}
|
||||
addMethodWithBestPosition(method, interfacz.getMethods());
|
||||
}
|
||||
|
||||
if (index == -1 || index >= methods.size()){
|
||||
interfacz.addMethod(method);
|
||||
} else {
|
||||
methods.add(index, method);
|
||||
}
|
||||
/**
|
||||
* 在最佳位置添加方法
|
||||
*
|
||||
* @param topLevelClass
|
||||
* @param method
|
||||
*/
|
||||
public static void addMethodWithBestPosition(TopLevelClass topLevelClass, Method method){
|
||||
addMethodWithBestPosition(method, topLevelClass.getMethods());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,4 +116,36 @@ public class FormatTools {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最佳添加位置
|
||||
*
|
||||
* @param method
|
||||
* @param methods
|
||||
* @return
|
||||
*/
|
||||
private static void addMethodWithBestPosition(Method method, List<Method> methods){
|
||||
int index = -1;
|
||||
for (int i = 0; i < methods.size(); i++){
|
||||
Method m = methods.get(i);
|
||||
if (m.getName().equals(method.getName())){
|
||||
if (m.getParameters().size() <= method.getParameters().size()){
|
||||
index = i + 1;
|
||||
} else {
|
||||
index = i;
|
||||
}
|
||||
} else if (m.getName().startsWith(method.getName())){
|
||||
if (index == - 1){
|
||||
index = i;
|
||||
}
|
||||
} else if (method.getName().startsWith(m.getName())){
|
||||
index = i + 1;
|
||||
}
|
||||
}
|
||||
if (index == -1 || index >= methods.size()){
|
||||
methods.add(methods.size(), method);
|
||||
} else {
|
||||
methods.add(index, method);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-15
@@ -96,10 +96,9 @@ public class IncrementsPluginTools {
|
||||
|
||||
/**
|
||||
* 是否启用了
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public boolean support(){
|
||||
public boolean support() {
|
||||
return this.columns.size() > 0;
|
||||
}
|
||||
|
||||
@@ -114,13 +113,12 @@ public class IncrementsPluginTools {
|
||||
|
||||
/**
|
||||
* 判断是否为需要进行增量操作的column
|
||||
*
|
||||
* @param searchColumn
|
||||
* @return
|
||||
*/
|
||||
public boolean supportColumn(IntrospectedColumn searchColumn){
|
||||
for (IntrospectedColumn column: this.columns){
|
||||
if (column.getActualColumnName().equals(searchColumn.getActualColumnName())){
|
||||
public boolean supportColumn(IntrospectedColumn searchColumn) {
|
||||
for (IntrospectedColumn column : this.columns) {
|
||||
if (column.getActualColumnName().equals(searchColumn.getActualColumnName())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -129,7 +127,6 @@ public class IncrementsPluginTools {
|
||||
|
||||
/**
|
||||
* 生成增量操作节点
|
||||
*
|
||||
* @param introspectedColumn
|
||||
* @param hasPrefix
|
||||
* @param hasComma
|
||||
@@ -146,18 +143,23 @@ public class IncrementsPluginTools {
|
||||
|
||||
// 没有启用增量操作
|
||||
XmlElement when = new XmlElement("when");
|
||||
when.addAttribute(new Attribute("test", (hasPrefix ? "record" : "_parameter") + ".incs.isEmpty()"));
|
||||
TextElement normal = new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null));
|
||||
when.addElement(normal);
|
||||
when.addAttribute(new Attribute(
|
||||
"test",
|
||||
(hasPrefix ? "record." : "_parameter.") + IncrementsPlugin.METHOD_INC_CHECK
|
||||
+ "('" + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + "')"
|
||||
));
|
||||
TextElement spec = new TextElement(
|
||||
MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn)
|
||||
+ " ${" + (hasPrefix ? "record." : "")
|
||||
+ IncrementsPlugin.FIELD_INC_MAP + "." + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + ".value} "
|
||||
+ MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null));
|
||||
when.addElement(spec);
|
||||
choose.addElement(when);
|
||||
|
||||
// 启用了增量操作
|
||||
XmlElement otherwise = new XmlElement("otherwise");
|
||||
TextElement spec = new TextElement(
|
||||
MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn)
|
||||
+ " ${" + (hasPrefix ? "record" : "_parameter") + ".incs." + MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn) + ".value} "
|
||||
+ MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null));
|
||||
otherwise.addElement(spec);
|
||||
TextElement normal = new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, hasPrefix ? "record." : null));
|
||||
otherwise.addElement(normal);
|
||||
choose.addElement(otherwise);
|
||||
|
||||
list.add(choose);
|
||||
|
||||
+1
@@ -63,6 +63,7 @@ public class TemplateCommentGenerator implements CommentGenerator {
|
||||
if (useForDefault){
|
||||
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(templatePath);
|
||||
doc = new SAXReader().read(inputStream);
|
||||
inputStream.close();
|
||||
} else {
|
||||
File file = new File(templatePath);
|
||||
if (file.exists()) {
|
||||
|
||||
@@ -210,7 +210,7 @@ public class BatchInsertPluginTest {
|
||||
String sql = SqlHelper.getFormatMapperSql(tbBlobsMapper.getObject(), "batchInsertSelective", params, columns);
|
||||
Assert.assertEquals(sql, "insert into tb_blobs ( field2 ) values ( 'null' ) , ( 'test123' )");
|
||||
// 2. 执行sql
|
||||
Object count = tbBlobsMapper.invokeVarArgs("batchInsertSelective", params, columns);
|
||||
Object count = tbBlobsMapper.invoke("batchInsertSelective", params, columns);
|
||||
Assert.assertEquals(count, 2);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
|
||||
@@ -16,6 +16,27 @@
|
||||
|
||||
package com.itfsw.mybatis.generator.plugins;
|
||||
|
||||
import com.itfsw.mybatis.generator.plugins.tools.DBHelper;
|
||||
import com.itfsw.mybatis.generator.plugins.tools.MyBatisGeneratorTool;
|
||||
import com.itfsw.mybatis.generator.plugins.tools.ObjectUtil;
|
||||
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.Method;
|
||||
import org.mybatis.generator.api.dom.java.TopLevelClass;
|
||||
import org.mybatis.generator.api.dom.xml.Document;
|
||||
import org.mybatis.generator.api.dom.xml.Element;
|
||||
import org.mybatis.generator.api.dom.xml.TextElement;
|
||||
import org.mybatis.generator.api.dom.xml.XmlElement;
|
||||
import org.mybatis.generator.config.MergeConstants;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* ---------------------------------------------------------------------------
|
||||
*
|
||||
@@ -25,4 +46,63 @@ package com.itfsw.mybatis.generator.plugins;
|
||||
* ---------------------------------------------------------------------------
|
||||
*/
|
||||
public class CommentPluginTest {
|
||||
/**
|
||||
* 初始化
|
||||
*/
|
||||
@BeforeClass
|
||||
public static void init() throws Exception {
|
||||
DBHelper.createDB("scripts/ComentPlugin/init.sql");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试没有配置模板的情况
|
||||
*/
|
||||
@Test
|
||||
public void testGenerateWithoutTemplate() throws Exception {
|
||||
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ComentPlugin/mybatis-generator-without-template.xml");
|
||||
MyBatisGenerator myBatisGenerator = tool.generate();
|
||||
// 是否在使用系统默认模板
|
||||
int count = 0;
|
||||
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
|
||||
if (file.getFormattedContent().indexOf("@project https://github.com/itfsw/mybatis-generator-plugin") != -1) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
Assert.assertTrue(count > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试配置了模板参数转换
|
||||
*/
|
||||
@Test
|
||||
public void testGenerateWithTemplate() throws Exception {
|
||||
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/ComentPlugin/mybatis-generator.xml");
|
||||
MyBatisGenerator myBatisGenerator = tool.generate();
|
||||
|
||||
// java中的注释
|
||||
for (GeneratedJavaFile file : myBatisGenerator.getGeneratedJavaFiles()) {
|
||||
if (file.getFileName().equals("Tb.java")) {
|
||||
TopLevelClass topLevelClass = (TopLevelClass) file.getCompilationUnit();
|
||||
// addJavaFileComment
|
||||
Assert.assertEquals(topLevelClass.getFileCommentLines().get(0), "TestAddJavaFileComment:Tb:" + new SimpleDateFormat("yyyy-MM").format(new Date()));
|
||||
// addFieldComment 同时测试 if 判断和 mbg
|
||||
Field id = topLevelClass.getFields().get(0);
|
||||
Assert.assertEquals(id.getJavaDocLines().get(0), "注释1");
|
||||
Assert.assertEquals(id.getJavaDocLines().get(1), MergeConstants.NEW_ELEMENT_TAG);
|
||||
// addGeneralMethodComment
|
||||
Method cons = topLevelClass.getMethods().get(0);
|
||||
Assert.assertEquals(cons.getJavaDocLines().get(0), "addGeneralMethodComment:Tb:tb");
|
||||
// addSetterComment
|
||||
Method setter = topLevelClass.getMethods().get(5);
|
||||
Assert.assertEquals(setter.getJavaDocLines().get(0), "addSetterComment:field1:field1");
|
||||
}
|
||||
}
|
||||
|
||||
// xml注释
|
||||
ObjectUtil xml = new ObjectUtil(myBatisGenerator.getGeneratedXmlFiles().get(0));
|
||||
Document doc = (Document) xml.get("document");
|
||||
List<Element> els = ((XmlElement) (doc.getRootElement().getElements().get(0))).getElements();
|
||||
String comment = ((TextElement) els.get(0)).getContent();
|
||||
Assert.assertEquals(comment, "addComment:BaseResultMap");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
/*
|
||||
* Copyright (c) 2017.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.itfsw.mybatis.generator.plugins;
|
||||
|
||||
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 java.lang.reflect.Method;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* ---------------------------------------------------------------------------
|
||||
*
|
||||
* ---------------------------------------------------------------------------
|
||||
* @author: hewei
|
||||
* @time:2017/7/5 15:32
|
||||
* ---------------------------------------------------------------------------
|
||||
*/
|
||||
public class IncrementsPluginTest {
|
||||
|
||||
/**
|
||||
* 初始化数据库
|
||||
*/
|
||||
@BeforeClass
|
||||
public static void init() throws Exception {
|
||||
DBHelper.createDB("scripts/IncrementsPlugin/init.sql");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试没有配置ModelBuilderPlugin
|
||||
*/
|
||||
@Test
|
||||
public void testWarningsWithoutModelBuilderPlugin() throws Exception {
|
||||
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator-without-model-builder-plugin.xml");
|
||||
tool.generate();
|
||||
|
||||
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.IncrementsPlugin插件需配合com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin插件使用!");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试ModelBuilder是否按配置正常生成了对应方法
|
||||
*/
|
||||
@Test
|
||||
public void testModelBuilderMethod() throws Exception {
|
||||
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator.xml");
|
||||
tool.generate(new AbstractShellCallback() {
|
||||
@Override
|
||||
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) {
|
||||
try {
|
||||
// 1. 测试生成的方法
|
||||
ObjectUtil tbBuilder = new ObjectUtil(loader, packagz + ".Tb$Builder");
|
||||
List<Method> methods = tbBuilder.getMethods("incF1");
|
||||
Assert.assertEquals(methods.size(), 2);
|
||||
// 自增方法
|
||||
Method incMethod = methods.get(0).getParameterTypes().length == 1 ? methods.get(1) : methods.get(0);
|
||||
Assert.assertEquals(incMethod.getParameters()[1].getParameterizedType().getTypeName(), packagz + ".Tb$Builder$Inc");
|
||||
|
||||
// 2. 测试有空格
|
||||
ObjectUtil tbKeysBuilder = new ObjectUtil(loader, packagz + ".TbKeys$Builder");
|
||||
Assert.assertEquals(tbKeysBuilder.getMethods("incF1").size(), 2);
|
||||
Assert.assertEquals(tbKeysBuilder.getMethods("incF2").size(), 2);
|
||||
Assert.assertEquals(tbKeysBuilder.getMethods("incF3").size(), 2);
|
||||
|
||||
// 3. 测试在WithBlobs正确生成
|
||||
ObjectUtil tbBlobsWithBLOBs = new ObjectUtil(loader, packagz + ".TbBlobsWithBLOBs$Builder");
|
||||
Assert.assertEquals(tbBlobsWithBLOBs.getMethods("incF1").size(), 2);
|
||||
Assert.assertEquals(tbBlobsWithBLOBs.getMethods("incF2").size(), 1);
|
||||
Assert.assertEquals(tbBlobsWithBLOBs.getMethods("incF3").size(), 2);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
Assert.assertTrue(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试生成的sql和具体执行
|
||||
*/
|
||||
@Test
|
||||
public void testSqlAndExecute() throws Exception {
|
||||
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/IncrementsPlugin/mybatis-generator.xml");
|
||||
tool.generate(new AbstractShellCallback() {
|
||||
@Override
|
||||
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) {
|
||||
try {
|
||||
// 1. 测试updateByExample、updateByExampleSelective
|
||||
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", 3l);
|
||||
|
||||
ObjectUtil tbBuilder = new ObjectUtil(loader, packagz + ".Tb$Builder");
|
||||
ObjectUtil tbBuilderInc = new ObjectUtil(loader, packagz + ".Tb$Builder$Inc#INC");
|
||||
tbBuilder.invoke("incF1", 100l, tbBuilderInc.getObject());
|
||||
|
||||
// sql
|
||||
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExample", tbBuilder.invoke("build"), tbExample.getObject());
|
||||
Assert.assertEquals(sql, "update tb set id = null, field1 = 'null', inc_f1 = inc_f1 + 100 , inc_f2 = null, inc_f3 = null WHERE ( id = '3' )");
|
||||
sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "updateByExampleSelective", tbBuilder.invoke("build"), tbExample.getObject());
|
||||
Assert.assertEquals(sql, "update tb SET inc_f1 = inc_f1 + 100 WHERE ( id = '3' )");
|
||||
// 执行
|
||||
// inc_f1 增加100
|
||||
Object result = tbMapper.invoke("updateByExampleSelective", tbBuilder.invoke("build"), tbExample.getObject());
|
||||
Assert.assertEquals(result, 1);
|
||||
PreparedStatement preparedStatement = sqlSession.getConnection().prepareStatement("select inc_f1 from tb where id = 3");
|
||||
preparedStatement.execute();
|
||||
ResultSet rs = preparedStatement.getResultSet();
|
||||
rs.first();
|
||||
Assert.assertEquals(rs.getInt("inc_f1"), 103);
|
||||
|
||||
// inc_f1 再减去50
|
||||
ObjectUtil tbBuilderDec = new ObjectUtil(loader, packagz + ".Tb$Builder$Inc#DEC");
|
||||
tbBuilder.invoke("incF1", 50l, tbBuilderDec.getObject());
|
||||
result = tbMapper.invoke("updateByExampleSelective", tbBuilder.invoke("build"), tbExample.getObject());
|
||||
Assert.assertEquals(result, 1);
|
||||
// 验证执行结果
|
||||
preparedStatement = sqlSession.getConnection().prepareStatement("select inc_f1 from tb where id = 3");
|
||||
preparedStatement.execute();
|
||||
rs = preparedStatement.getResultSet();
|
||||
rs.first();
|
||||
Assert.assertEquals(rs.getInt("inc_f1"), 53);
|
||||
|
||||
|
||||
// 2. 测试updateByPrimaryKey、updateByPrimaryKeySelective
|
||||
ObjectUtil tbKeysMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbKeysMapper")));
|
||||
|
||||
ObjectUtil tbKeysBuilderInc = new ObjectUtil(loader, packagz + ".TbKeys$Builder$Inc#INC");
|
||||
|
||||
ObjectUtil tbKeysBuilder = new ObjectUtil(loader, packagz + ".TbKeys$Builder");
|
||||
tbKeysBuilder.invoke("key1", 1l);
|
||||
tbKeysBuilder.invoke("key2", "k1");
|
||||
tbKeysBuilder.invoke("incF1", 10l, tbKeysBuilderInc.getObject());
|
||||
tbKeysBuilder.invoke("incF3", 30l, tbKeysBuilderInc.getObject());
|
||||
|
||||
// sql
|
||||
sql = SqlHelper.getFormatMapperSql(tbKeysMapper.getObject(), "updateByPrimaryKey", tbKeysBuilder.invoke("build"));
|
||||
Assert.assertEquals(sql, "update tb_keys set field1 = 'null', field2 = null, inc_f1 = inc_f1 + 10 , inc_f2 = null , inc_f3 = inc_f3 + 30 where key1 = 1 and key2 = 'k1'");
|
||||
sql = SqlHelper.getFormatMapperSql(tbKeysMapper.getObject(), "updateByPrimaryKeySelective", tbKeysBuilder.invoke("build"));
|
||||
Assert.assertEquals(sql, "update tb_keys SET inc_f1 = inc_f1 + 10 , inc_f3 = inc_f3 + 30 where key1 = 1 and key2 = 'k1'");
|
||||
// 执行
|
||||
result = tbKeysMapper.invoke("updateByPrimaryKeySelective", tbKeysBuilder.invoke("build"));
|
||||
Assert.assertEquals(result, 1);
|
||||
// 验证执行结果
|
||||
preparedStatement = sqlSession.getConnection().prepareStatement("select inc_f1, inc_f3 from tb_keys where key1 = 1 and key2 = 'k1'");
|
||||
preparedStatement.execute();
|
||||
rs = preparedStatement.getResultSet();
|
||||
rs.first();
|
||||
Assert.assertEquals(rs.getInt("inc_f1"), 11);
|
||||
Assert.assertEquals(rs.getInt("inc_f3"), 33);
|
||||
|
||||
// 3. 测试updateByExampleWithBLOBs、updateByPrimaryKeyWithBLOBs
|
||||
ObjectUtil tbBlobsMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbBlobsMapper")));
|
||||
|
||||
ObjectUtil tbBlobsExample = new ObjectUtil(loader, packagz + ".TbBlobsExample");
|
||||
ObjectUtil tbBlobsExampleCriteria = new ObjectUtil(tbBlobsExample.invoke("createCriteria"));
|
||||
tbBlobsExampleCriteria.invoke("andIdEqualTo", 3l);
|
||||
|
||||
ObjectUtil tbBlobsWithBLOBsBuilder = new ObjectUtil(loader, packagz + ".TbBlobsWithBLOBs$Builder");
|
||||
ObjectUtil tbBlobsBuilderInc = new ObjectUtil(loader, packagz + ".TbBlobs$Builder$Inc#INC");
|
||||
tbBlobsWithBLOBsBuilder.invoke("incF1", 100l, tbBlobsBuilderInc.getObject());
|
||||
tbBlobsWithBLOBsBuilder.invoke("incF2", 50l);
|
||||
tbBlobsWithBLOBsBuilder.invoke("field3", "blob");
|
||||
|
||||
// sql
|
||||
sql = SqlHelper.getFormatMapperSql(tbBlobsMapper.getObject(), "updateByExampleWithBLOBs", tbBlobsWithBLOBsBuilder.invoke("build"), tbBlobsExample.getObject());
|
||||
Assert.assertEquals(sql, "update tb_blobs set id = null, field1 = 'null', inc_f1 = inc_f1 + 100 , inc_f2 = 50, inc_f3 = null , field2 = 'null', field3 = 'blob' WHERE ( id = '3' )");
|
||||
|
||||
tbBlobsWithBLOBsBuilder.invoke("id", 3l);
|
||||
sql = SqlHelper.getFormatMapperSql(tbBlobsMapper.getObject(), "updateByPrimaryKeyWithBLOBs", tbBlobsWithBLOBsBuilder.invoke("build"));
|
||||
Assert.assertEquals(sql, "update tb_blobs set field1 = 'null', inc_f1 = inc_f1 + 100 , inc_f2 = 50, inc_f3 = null , field2 = 'null', field3 = 'blob' where id = 3");
|
||||
|
||||
// 执行
|
||||
tbBlobsWithBLOBsBuilder.invoke("incF3", 10l);
|
||||
// 测试自增字段没有配置自增参数
|
||||
sql = SqlHelper.getFormatMapperSql(tbBlobsMapper.getObject(), "updateByPrimaryKeyWithBLOBs", tbBlobsWithBLOBsBuilder.invoke("build"));
|
||||
Assert.assertEquals(sql, "update tb_blobs set field1 = 'null', inc_f1 = inc_f1 + 100 , inc_f2 = 50, inc_f3 = 10 , field2 = 'null', field3 = 'blob' where id = 3");
|
||||
result = tbBlobsMapper.invoke("updateByPrimaryKeyWithBLOBs", tbBlobsWithBLOBsBuilder.invoke("build"));
|
||||
Assert.assertEquals(result, 1);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
Assert.assertTrue(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ public class SelectSelectivePluginTest {
|
||||
|
||||
|
||||
// 2. 执行sql
|
||||
List list = (List) tbMapper.invokeVarArgs("selectByExampleSelective", tbExample.getObject(), columns1);
|
||||
List list = (List) tbMapper.invoke("selectByExampleSelective", tbExample.getObject(), columns1);
|
||||
Assert.assertEquals(list.size(), 3);
|
||||
int index = 0;
|
||||
for (Object obj : list) {
|
||||
@@ -143,7 +143,7 @@ public class SelectSelectivePluginTest {
|
||||
Assert.assertEquals(sql, "select field2 from tb_keys where key1 = 1 and key2 = '2'");
|
||||
|
||||
// 3. 执行sql
|
||||
Object tbKeys = tbKeysMapper.invokeVarArgs("selectByPrimaryKeySelective", tbKeysKey.getObject(), columns1);
|
||||
Object tbKeys = tbKeysMapper.invoke("selectByPrimaryKeySelective", tbKeysKey.getObject(), columns1);
|
||||
Assert.assertEquals(new ObjectUtil(tbKeys).get("field1"), "fd1");
|
||||
|
||||
} catch (Exception e) {
|
||||
@@ -195,7 +195,7 @@ public class SelectSelectivePluginTest {
|
||||
Assert.assertEquals(sql, "select field1 from tb WHERE ( id = '3' ) order by field2 asc limit 1");
|
||||
|
||||
// 2. 执行sql
|
||||
Object result = tbMapper.invokeVarArgs("selectOneByExampleSelective", tbExample.getObject(), columns1);
|
||||
Object result = tbMapper.invoke("selectOneByExampleSelective", tbExample.getObject(), columns1);
|
||||
ObjectUtil tb = new ObjectUtil(result);
|
||||
Assert.assertEquals(tb.get("field1"), "fd3");
|
||||
Assert.assertNull(tb.get("field2"));
|
||||
|
||||
@@ -16,9 +16,12 @@
|
||||
|
||||
package com.itfsw.mybatis.generator.plugins.tools;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* ---------------------------------------------------------------------------
|
||||
@@ -107,7 +110,7 @@ public class ObjectUtil {
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行方法
|
||||
* 执行方法(mapper动态代理后VarArgs检查有问题)
|
||||
* @param methodName
|
||||
* @param args
|
||||
* @return
|
||||
@@ -116,12 +119,15 @@ public class ObjectUtil {
|
||||
* @throws IllegalAccessException
|
||||
*/
|
||||
public Object invoke(String methodName, Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||
Method[] methods = this.cls.getDeclaredMethods();
|
||||
List<Method> methods = getMethods(methodName);
|
||||
for (Method method : methods) {
|
||||
if (method.getName().equals(methodName) && method.getParameterTypes().length == args.length) {
|
||||
if (method.getParameterTypes().length == args.length) {
|
||||
boolean flag = true;
|
||||
Class[] parameterTypes = method.getParameterTypes();
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
// !! mapper动态代理后VarArgs检查有问题
|
||||
// 暂时只检查前几位相同就假设为可变参数
|
||||
int check = args.length > 0 ? (args[args.length - 1] instanceof Array ? args.length - 1 : args.length) : 0;
|
||||
for (int i = 0; i < check; i++) {
|
||||
if (!(parameterTypes[i].isAssignableFrom(args[i].getClass()))) {
|
||||
flag = false;
|
||||
}
|
||||
@@ -132,26 +138,26 @@ public class ObjectUtil {
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
throw new NoSuchMethodError("没有找到方法:" + methodName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行方法(mapper动态代理后VarArgs检查有问题)
|
||||
* @param methodName
|
||||
* @param args
|
||||
* 获取指定名称的方法
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
* @throws NoSuchMethodException
|
||||
* @throws InvocationTargetException
|
||||
* @throws IllegalAccessException
|
||||
*/
|
||||
public Object invokeVarArgs(String methodName, Object... args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
|
||||
Method[] methods = this.cls.getDeclaredMethods();
|
||||
for (Method method : methods) {
|
||||
if (method.getName().equals(methodName)) {
|
||||
return method.invoke(this.object, args);
|
||||
public List<Method> getMethods(String name){
|
||||
List<Method> list = new ArrayList<>();
|
||||
Class clazz = this.cls;
|
||||
for (; clazz != Object.class; clazz = clazz.getSuperclass()){
|
||||
for (Method method : clazz.getDeclaredMethods()){
|
||||
if (method.getName().equals(name)){
|
||||
list.add(method);
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -127,12 +127,10 @@ public class SqlHelper {
|
||||
}
|
||||
}
|
||||
if (args != null && args.length == 1) {
|
||||
Object _params = wrapCollection(args[0]);
|
||||
if (_params instanceof Map) {
|
||||
params.putAll((Map) _params);
|
||||
}
|
||||
return getNamespaceSql(session, fullMapperMethodName, args[0]);
|
||||
} else {
|
||||
return getNamespaceSql(session, fullMapperMethodName, params);
|
||||
}
|
||||
return getNamespaceSql(session, fullMapperMethodName, params);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
Navicat MySQL Data Transfer
|
||||
|
||||
Source Server : localhost
|
||||
Source Server Version : 50617
|
||||
Source Host : localhost:3306
|
||||
Source Database : mybatis-generator-plugin
|
||||
|
||||
Target Server Type : MYSQL
|
||||
Target Server Version : 50617
|
||||
File Encoding : 65001
|
||||
|
||||
Date: 2017-06-26 17:30:13
|
||||
*/
|
||||
|
||||
SET FOREIGN_KEY_CHECKS=0;
|
||||
|
||||
-- ----------------------------
|
||||
-- Table structure for tb
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `tb`;
|
||||
CREATE TABLE `tb` (
|
||||
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
|
||||
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
|
||||
PRIMARY KEY (`id`)
|
||||
);
|
||||
|
||||
-- ----------------------------
|
||||
-- Records of tb
|
||||
-- ----------------------------
|
||||
@@ -0,0 +1,55 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017.
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<!DOCTYPE generatorConfiguration
|
||||
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
|
||||
<generatorConfiguration>
|
||||
<properties resource="db.properties"/>
|
||||
|
||||
<!--导入属性配置 -->
|
||||
<context id="default" targetRuntime="MyBatis3">
|
||||
<!-- 插件 -->
|
||||
<!-- 注释插件 -->
|
||||
<plugin type="com.itfsw.mybatis.generator.plugins.CommentPlugin" />
|
||||
<plugin type="com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin" />
|
||||
|
||||
<!--jdbc的数据库连接 -->
|
||||
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
|
||||
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
|
||||
targetPackage 指定生成的model生成所在的包名
|
||||
targetProject 指定在该项目下所在的路径 -->
|
||||
<javaModelGenerator targetPackage="" targetProject="">
|
||||
<!-- 是否对model添加 构造函数 -->
|
||||
<property name="constructorBased" value="true"/>
|
||||
<!-- 给Model添加一个父类 -->
|
||||
<!--<property name="rootClass" value="com.itfsw.base"/>-->
|
||||
</javaModelGenerator>
|
||||
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
|
||||
<sqlMapGenerator targetPackage="" targetProject="" />
|
||||
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
|
||||
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
|
||||
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
|
||||
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
|
||||
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
|
||||
|
||||
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
|
||||
<table tableName="tb">
|
||||
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
|
||||
</table>
|
||||
</context>
|
||||
</generatorConfiguration>
|
||||
@@ -0,0 +1,60 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017.
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<!DOCTYPE generatorConfiguration
|
||||
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
|
||||
<generatorConfiguration>
|
||||
<properties resource="db.properties"/>
|
||||
|
||||
<!--导入属性配置 -->
|
||||
<context id="default" targetRuntime="MyBatis3">
|
||||
<!-- 插件 -->
|
||||
<!-- 注释插件 -->
|
||||
<plugin type="com.itfsw.mybatis.generator.plugins.CommentPlugin">
|
||||
<property name="template" value="src/test/resources/scripts/ComentPlugin/test-comment.ftl"/>
|
||||
</plugin>
|
||||
<plugin type="com.itfsw.mybatis.generator.plugins.ExampleEnhancedPlugin" />
|
||||
|
||||
<commentGenerator>
|
||||
<property name="addRemarkComments" value="true"/>
|
||||
</commentGenerator>
|
||||
<!--jdbc的数据库连接 -->
|
||||
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
|
||||
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
|
||||
targetPackage 指定生成的model生成所在的包名
|
||||
targetProject 指定在该项目下所在的路径 -->
|
||||
<javaModelGenerator targetPackage="" targetProject="">
|
||||
<!-- 是否对model添加 构造函数 -->
|
||||
<property name="constructorBased" value="true"/>
|
||||
<!-- 给Model添加一个父类 -->
|
||||
<!--<property name="rootClass" value="com.itfsw.base"/>-->
|
||||
</javaModelGenerator>
|
||||
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
|
||||
<sqlMapGenerator targetPackage="" targetProject="" />
|
||||
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
|
||||
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
|
||||
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
|
||||
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
|
||||
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
|
||||
|
||||
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
|
||||
<table tableName="tb">
|
||||
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
|
||||
</table>
|
||||
</context>
|
||||
</generatorConfiguration>
|
||||
@@ -0,0 +1,238 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<template>
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* This method is called to add a file level comment to a generated java file. This method could be used to add a
|
||||
* general file comment (such as a copyright notice). However, note that the Java file merge function in Eclipse
|
||||
* does not deal with this comment. If you run the generator repeatedly, you will only retain the comment from the
|
||||
* initial run.
|
||||
* <p>
|
||||
*
|
||||
* The default implementation does nothing.
|
||||
*
|
||||
* @param compilationUnit
|
||||
* the compilation unit
|
||||
*/
|
||||
-->
|
||||
<comment ID="addJavaFileComment"><![CDATA[
|
||||
TestAddJavaFileComment:${compilationUnit.type.shortName}:${.now?string("yyyy-MM")}
|
||||
]]></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* This method should add a suitable comment as a child element of the specified xmlElement to warn users that the
|
||||
* element was generated and is subject to regeneration.
|
||||
*
|
||||
* @param xmlElement
|
||||
* the xml element
|
||||
*/
|
||||
-->
|
||||
<comment ID="addComment"><![CDATA[
|
||||
addComment:${xmlElement.attributes[0].value}
|
||||
]]></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* This method is called to add a comment as the first child of the root element. This method could be used to add a
|
||||
* general file comment (such as a copyright notice). However, note that the XML file merge function does not deal
|
||||
* with this comment. If you run the generator repeatedly, you will only retain the comment from the initial run.
|
||||
* <p>
|
||||
*
|
||||
* The default implementation does nothing.
|
||||
*
|
||||
* @param rootElement
|
||||
* the root element
|
||||
*/
|
||||
-->
|
||||
<comment ID="addRootComment"></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* This method should add a Javadoc comment to the specified field. The field is related to the specified table and
|
||||
* is used to hold the value of the specified column.
|
||||
* <p>
|
||||
*
|
||||
* <b>Important:</b> This method should add a the nonstandard JavaDoc tag "@mbg.generated" to the comment. Without
|
||||
* this tag, the Eclipse based Java merge feature will fail.
|
||||
*
|
||||
* @param field
|
||||
* the field
|
||||
* @param introspectedTable
|
||||
* the introspected table
|
||||
* @param introspectedColumn
|
||||
* the introspected column
|
||||
*/
|
||||
-->
|
||||
<comment ID="addFieldComment"><![CDATA[
|
||||
<#if introspectedColumn??>
|
||||
<#if introspectedColumn.remarks?? && introspectedColumn.remarks != ''>
|
||||
<#list introspectedColumn.remarks?split("\n") as remark>
|
||||
${remark}
|
||||
</#list>
|
||||
</#if>
|
||||
${mgb}
|
||||
</#if>
|
||||
]]></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* Adds a comment for a model class. The Java code merger should
|
||||
* be notified not to delete the entire class in case any manual
|
||||
* changes have been made. So this method will always use the
|
||||
* "do not delete" annotation.
|
||||
*
|
||||
* Because of difficulties with the Java file merger, the default implementation
|
||||
* of this method should NOT add comments. Comments should only be added if
|
||||
* specifically requested by the user (for example, by enabling table remark comments).
|
||||
*
|
||||
* @param topLevelClass
|
||||
* the top level class
|
||||
* @param introspectedTable
|
||||
* the introspected table
|
||||
*/
|
||||
-->
|
||||
<comment ID="addModelClassComment"><![CDATA[
|
||||
/**
|
||||
<#if introspectedTable.remarks?? && introspectedTable.remarks != ''>
|
||||
* Database Table Remarks:
|
||||
<#list introspectedTable.remarks?split("\n") as remark>
|
||||
* ${remark}
|
||||
</#list>
|
||||
</#if>
|
||||
*
|
||||
* This class was generated by MyBatis Generator.
|
||||
* This class corresponds to the database table ${introspectedTable.fullyQualifiedTable}
|
||||
*
|
||||
* ${mgb} do_not_delete_during_merge
|
||||
* @project https://github.com/itfsw/mybatis-generator-plugin
|
||||
*/
|
||||
]]></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* Adds the inner class comment.
|
||||
*
|
||||
* @param innerClass
|
||||
* the inner class
|
||||
* @param introspectedTable
|
||||
* the introspected table
|
||||
* @param markAsDoNotDelete
|
||||
* the mark as do not delete
|
||||
*/
|
||||
-->
|
||||
<comment ID="addClassComment"><![CDATA[
|
||||
/**
|
||||
* This class was generated by MyBatis Generator.
|
||||
* This class corresponds to the database table ${introspectedTable.fullyQualifiedTable}
|
||||
*
|
||||
* ${mgb}<#if markAsDoNotDelete?? && markAsDoNotDelete> do_not_delete_during_merge</#if>
|
||||
* @project https://github.com/itfsw/mybatis-generator-plugin
|
||||
*/
|
||||
]]></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* Adds the enum comment.
|
||||
*
|
||||
* @param innerEnum
|
||||
* the inner enum
|
||||
* @param introspectedTable
|
||||
* the introspected table
|
||||
*/
|
||||
-->
|
||||
<comment ID="addEnumComment"><![CDATA[
|
||||
/**
|
||||
* This enum was generated by MyBatis Generator.
|
||||
* This enum corresponds to the database table ${introspectedTable.fullyQualifiedTable}
|
||||
*
|
||||
* ${mgb}
|
||||
* @project https://github.com/itfsw/mybatis-generator-plugin
|
||||
*/
|
||||
]]></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* Adds the interface comment.
|
||||
*
|
||||
* @param innerInterface
|
||||
* the inner interface
|
||||
* @param introspectedTable
|
||||
* the introspected table
|
||||
*/
|
||||
-->
|
||||
<comment ID="addInterfaceComment"><![CDATA[
|
||||
/**
|
||||
* This interface was generated by MyBatis Generator.
|
||||
* This interface corresponds to the database table ${introspectedTable.fullyQualifiedTable}
|
||||
*
|
||||
* ${mgb}
|
||||
* @project https://github.com/itfsw/mybatis-generator-plugin
|
||||
*/
|
||||
]]></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* Adds the getter comment.
|
||||
*
|
||||
* @param method
|
||||
* the method
|
||||
* @param introspectedTable
|
||||
* the introspected table
|
||||
* @param introspectedColumn
|
||||
* the introspected column
|
||||
*/
|
||||
-->
|
||||
<comment ID="addGetterComment"><![CDATA[
|
||||
<#if introspectedColumn??>
|
||||
/**
|
||||
* This method was generated by MyBatis Generator.
|
||||
* This method returns the value of the database column ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
|
||||
*
|
||||
* @return the value of ${introspectedTable.fullyQualifiedTable}.${introspectedColumn.actualColumnName}
|
||||
*
|
||||
* ${mgb}
|
||||
* @project https://github.com/itfsw/mybatis-generator-plugin
|
||||
*/
|
||||
<#else>
|
||||
/**
|
||||
* This method was generated by MyBatis Generator.
|
||||
* This method returns the value of the field ${method.name?replace("get","")?replace("is", "")?uncap_first}
|
||||
*
|
||||
* @return the value of field ${method.name?replace("get","")?replace("is", "")?uncap_first}
|
||||
*
|
||||
* ${mgb}
|
||||
* @project https://github.com/itfsw/mybatis-generator-plugin
|
||||
*/
|
||||
</#if>
|
||||
]]></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* Adds the setter comment.
|
||||
*
|
||||
* @param method
|
||||
* the method
|
||||
* @param introspectedTable
|
||||
* the introspected table
|
||||
* @param introspectedColumn
|
||||
* the introspected column
|
||||
*/
|
||||
-->
|
||||
<comment ID="addSetterComment"><![CDATA[
|
||||
addSetterComment:${method.name?replace("set","")?uncap_first}:${method.parameters[0].name}
|
||||
]]></comment>
|
||||
|
||||
<!-- #############################################################################################################
|
||||
/**
|
||||
* Adds the general method comment.
|
||||
*
|
||||
* @param method
|
||||
* the method
|
||||
* @param introspectedTable
|
||||
* the introspected table
|
||||
*/
|
||||
-->
|
||||
<comment ID="addGeneralMethodComment"><![CDATA[
|
||||
addGeneralMethodComment:${method.name}:${introspectedTable.fullyQualifiedTable}
|
||||
]]></comment>
|
||||
</template>
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
Navicat MySQL Data Transfer
|
||||
|
||||
Source Server : localhost
|
||||
Source Server Version : 50617
|
||||
Source Host : localhost:3306
|
||||
Source Database : mybatis-generator-plugin
|
||||
|
||||
Target Server Type : MYSQL
|
||||
Target Server Version : 50617
|
||||
File Encoding : 65001
|
||||
|
||||
Date: 2017-07-05 17:21:41
|
||||
*/
|
||||
|
||||
SET FOREIGN_KEY_CHECKS=0;
|
||||
|
||||
-- ----------------------------
|
||||
-- Table structure for tb
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `tb`;
|
||||
CREATE TABLE `tb` (
|
||||
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
|
||||
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
|
||||
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
|
||||
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
|
||||
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
|
||||
|
||||
-- ----------------------------
|
||||
-- Records of tb
|
||||
-- ----------------------------
|
||||
INSERT INTO `tb` VALUES ('1', 'fd1', '0', '0', '0');
|
||||
INSERT INTO `tb` VALUES ('2', 'fd2', '1', '2', '3');
|
||||
INSERT INTO `tb` VALUES ('3', null, '3', '2', '1');
|
||||
INSERT INTO `tb` VALUES ('4', 'fd3', '1', '1', '1');
|
||||
|
||||
-- ----------------------------
|
||||
-- Table structure for tb_blobs
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `tb_blobs`;
|
||||
CREATE TABLE `tb_blobs` (
|
||||
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
|
||||
`field1` varchar(255) DEFAULT NULL,
|
||||
`field2` longtext COMMENT '注释2',
|
||||
`field3` longtext,
|
||||
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
|
||||
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
|
||||
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
|
||||
|
||||
-- ----------------------------
|
||||
-- Records of tb_blobs
|
||||
-- ----------------------------
|
||||
INSERT INTO `tb_blobs` VALUES ('1', 'fd1', null, null, '1', '2', '3');
|
||||
INSERT INTO `tb_blobs` VALUES ('2', null, 'fd2', null, '3', '2', '1');
|
||||
INSERT INTO `tb_blobs` VALUES ('3', null, null, 'fd3', '1', '1', '1');
|
||||
INSERT INTO `tb_blobs` VALUES ('4', 'fd4', 'fd5', 'fd6', '0', '0', '0');
|
||||
|
||||
-- ----------------------------
|
||||
-- Table structure for tb_keys
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `tb_keys`;
|
||||
CREATE TABLE `tb_keys` (
|
||||
`key1` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
|
||||
`key2` varchar(255) NOT NULL,
|
||||
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
|
||||
`field2` int(11) DEFAULT NULL,
|
||||
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
|
||||
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
|
||||
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
|
||||
PRIMARY KEY (`key1`,`key2`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
|
||||
|
||||
-- ----------------------------
|
||||
-- Records of tb_keys
|
||||
-- ----------------------------
|
||||
INSERT INTO `tb_keys` VALUES ('1', 'k1', 'fd1', null, '1', '2', '3');
|
||||
INSERT INTO `tb_keys` VALUES ('2', 'k2', null, '2', '3', '2', '1');
|
||||
INSERT INTO `tb_keys` VALUES ('3', 'k3', null, null, '1', '1', '1');
|
||||
|
||||
-- ----------------------------
|
||||
-- Table structure for tb_single_blob
|
||||
-- ----------------------------
|
||||
DROP TABLE IF EXISTS `tb_single_blob`;
|
||||
CREATE TABLE `tb_single_blob` (
|
||||
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
|
||||
`field1` longtext COMMENT '注释2',
|
||||
`field2` int(11) DEFAULT NULL,
|
||||
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
|
||||
`inc_f2` bigint(20) NOT NULL DEFAULT '0',
|
||||
`inc_f3` bigint(20) NOT NULL DEFAULT '0',
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
|
||||
|
||||
-- ----------------------------
|
||||
-- Records of tb_single_blob
|
||||
-- ----------------------------
|
||||
INSERT INTO `tb_single_blob` VALUES ('1', 'fd1', '0', '1', '2', '3');
|
||||
INSERT INTO `tb_single_blob` VALUES ('2', null, null, '3', '2', '1');
|
||||
INSERT INTO `tb_single_blob` VALUES ('3', null, null, '1', '1', '1');
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017.
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<!DOCTYPE generatorConfiguration
|
||||
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
|
||||
<generatorConfiguration>
|
||||
<properties resource="db.properties"/>
|
||||
|
||||
<!--导入属性配置 -->
|
||||
<context id="default" targetRuntime="MyBatis3">
|
||||
<!-- 插件 -->
|
||||
<plugin type="com.itfsw.mybatis.generator.plugins.IncrementsPlugin" />
|
||||
|
||||
<!--jdbc的数据库连接 -->
|
||||
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
|
||||
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
|
||||
targetPackage 指定生成的model生成所在的包名
|
||||
targetProject 指定在该项目下所在的路径 -->
|
||||
<javaModelGenerator targetPackage="" targetProject="">
|
||||
<!-- 是否对model添加 构造函数 -->
|
||||
<property name="constructorBased" value="true"/>
|
||||
<!-- 给Model添加一个父类 -->
|
||||
<!--<property name="rootClass" value="com.itfsw.base"/>-->
|
||||
</javaModelGenerator>
|
||||
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
|
||||
<sqlMapGenerator targetPackage="" targetProject="" />
|
||||
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
|
||||
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
|
||||
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
|
||||
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
|
||||
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
|
||||
|
||||
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
|
||||
<table tableName="tb">
|
||||
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
|
||||
</table>
|
||||
</context>
|
||||
</generatorConfiguration>
|
||||
@@ -0,0 +1,62 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017.
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<!DOCTYPE generatorConfiguration
|
||||
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
|
||||
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
|
||||
<generatorConfiguration>
|
||||
<properties resource="db.properties"/>
|
||||
|
||||
<!--导入属性配置 -->
|
||||
<context id="default" targetRuntime="MyBatis3">
|
||||
<!-- 插件 -->
|
||||
<plugin type="com.itfsw.mybatis.generator.plugins.IncrementsPlugin" />
|
||||
<plugin type="com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin" />
|
||||
|
||||
<!--jdbc的数据库连接 -->
|
||||
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
|
||||
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
|
||||
targetPackage 指定生成的model生成所在的包名
|
||||
targetProject 指定在该项目下所在的路径 -->
|
||||
<javaModelGenerator targetPackage="" targetProject="">
|
||||
<!-- 是否对model添加 构造函数 -->
|
||||
<property name="constructorBased" value="true"/>
|
||||
<!-- 给Model添加一个父类 -->
|
||||
<!--<property name="rootClass" value="com.itfsw.base"/>-->
|
||||
</javaModelGenerator>
|
||||
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
|
||||
<sqlMapGenerator targetPackage="" targetProject="" />
|
||||
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
|
||||
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
|
||||
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
|
||||
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
|
||||
<javaClientGenerator targetPackage="" targetProject="" type="XMLMAPPER"/>
|
||||
|
||||
<!-- +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 要自动生成的表 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
|
||||
<table tableName="tb">
|
||||
<property name="incrementsColumns" value="inc_f1"/>
|
||||
|
||||
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
|
||||
</table>
|
||||
<table tableName="tb_keys">
|
||||
<property name="incrementsColumns" value=" inc_f1, inc_f2, inc_f3 "/>
|
||||
</table>
|
||||
<table tableName="tb_blobs">
|
||||
<property name="incrementsColumns" value="inc_f1,inc_f3"/>
|
||||
</table>
|
||||
</context>
|
||||
</generatorConfiguration>
|
||||
Reference in New Issue
Block a user