Commit 331634de authored by hewei's avatar hewei

乐观锁插件实现

parent ab702538
...@@ -335,9 +335,9 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH ...@@ -335,9 +335,9 @@ public class IncrementsPlugin extends BasePlugin implements IModelBuilderPluginH
private void generatedWithSelective(XmlElement element, IntrospectedTable introspectedTable, boolean hasPrefix) { private void generatedWithSelective(XmlElement element, IntrospectedTable introspectedTable, boolean hasPrefix) {
if (incTools.support()) { if (incTools.support()) {
// 查找 set->if->text // 查找 set->if->text
List<XmlElement> sets = XmlElementGeneratorTools.findXmlElements(element, "set"); List<XmlElement> sets = XmlElementTools.findXmlElements(element, "set");
if (sets.size() > 0) { if (sets.size() > 0) {
List<XmlElement> ifs = XmlElementGeneratorTools.findXmlElements(sets.get(0), "if"); List<XmlElement> ifs = XmlElementTools.findXmlElements(sets.get(0), "if");
if (ifs.size() > 0) { if (ifs.size() > 0) {
for (XmlElement xmlElement : ifs) { for (XmlElement xmlElement : ifs) {
// 下面为if的text节点 // 下面为if的text节点
......
...@@ -567,7 +567,7 @@ public class LogicalDeletePlugin extends BasePlugin { ...@@ -567,7 +567,7 @@ public class LogicalDeletePlugin extends BasePlugin {
innerClass.addMethod(method); innerClass.addMethod(method);
// TODO 过期方法 // TODO 过期方法
Method mAndDeleted = JavaElementGeneratorTools.cloneMethod(method); Method mAndDeleted = new Method(method);
mAndDeleted.setName("andDeleted"); mAndDeleted.setName("andDeleted");
mAndDeleted.addAnnotation("@Deprecated"); mAndDeleted.addAnnotation("@Deprecated");
innerClass.addMethod(mAndDeleted); innerClass.addMethod(mAndDeleted);
......
...@@ -16,9 +16,7 @@ ...@@ -16,9 +16,7 @@
package com.itfsw.mybatis.generator.plugins; package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin; import com.itfsw.mybatis.generator.plugins.utils.*;
import com.itfsw.mybatis.generator.plugins.utils.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.hook.IIncrementsPluginHook; import com.itfsw.mybatis.generator.plugins.utils.hook.IIncrementsPluginHook;
import com.itfsw.mybatis.generator.plugins.utils.hook.IUpsertPluginHook; import com.itfsw.mybatis.generator.plugins.utils.hook.IUpsertPluginHook;
import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedColumn;
...@@ -82,8 +80,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin ...@@ -82,8 +80,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME); FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true)); method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
method.getJavaDocLines().clear(); FormatTools.replaceGeneralMethodComment(commentGenerator, method, introspectedTable);
commentGenerator.addGeneralMethodComment(method, introspectedTable);
return super.clientInsertSelectiveMethodGenerated(method, interfaze, introspectedTable); return super.clientInsertSelectiveMethodGenerated(method, interfaze, introspectedTable);
} }
...@@ -112,8 +109,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin ...@@ -112,8 +109,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME); FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true)); method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
method.getJavaDocLines().clear(); FormatTools.replaceGeneralMethodComment(commentGenerator, method, introspectedTable);
commentGenerator.addGeneralMethodComment(method, introspectedTable);
return super.clientUpdateByExampleSelectiveMethodGenerated(method, interfaze, introspectedTable); return super.clientUpdateByExampleSelectiveMethodGenerated(method, interfaze, introspectedTable);
} }
...@@ -144,8 +140,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin ...@@ -144,8 +140,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin
FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME); FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(fullFieldModel.getShortName() + "." + ModelColumnPlugin.ENUM_NAME);
method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true)); method.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
method.getJavaDocLines().clear(); FormatTools.replaceGeneralMethodComment(commentGenerator, method, introspectedTable);
commentGenerator.addGeneralMethodComment(method, introspectedTable);
return super.clientUpdateByPrimaryKeySelectiveMethodGenerated(method, interfaze, introspectedTable); return super.clientUpdateByPrimaryKeySelectiveMethodGenerated(method, interfaze, introspectedTable);
} }
...@@ -194,7 +189,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin ...@@ -194,7 +189,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin
answer.addElement(new TextElement("values")); answer.addElement(new TextElement("values"));
answer.addElement(this.generateInsertValuesSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns()))); answer.addElement(this.generateInsertValuesSelective(ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns())));
XmlElementGeneratorTools.replaceXmlElement(element, answer); XmlElementTools.replaceXmlElement(element, answer);
return super.sqlMapInsertSelectiveElementGenerated(element, introspectedTable); return super.sqlMapInsertSelectiveElementGenerated(element, introspectedTable);
} }
...@@ -226,7 +221,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin ...@@ -226,7 +221,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin
answer.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable)); answer.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
XmlElementGeneratorTools.replaceXmlElement(element, answer); XmlElementTools.replaceXmlElement(element, answer);
return super.sqlMapUpdateByExampleSelectiveElementGenerated(element, introspectedTable); return super.sqlMapUpdateByExampleSelectiveElementGenerated(element, introspectedTable);
} }
...@@ -259,7 +254,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin ...@@ -259,7 +254,7 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin
XmlElementGeneratorTools.generateWhereByPrimaryKeyTo(answer, introspectedTable.getPrimaryKeyColumns(), "record."); XmlElementGeneratorTools.generateWhereByPrimaryKeyTo(answer, introspectedTable.getPrimaryKeyColumns(), "record.");
XmlElementGeneratorTools.replaceXmlElement(element, answer); XmlElementTools.replaceXmlElement(element, answer);
return super.sqlMapUpdateByPrimaryKeySelectiveElementGenerated(element, introspectedTable); return super.sqlMapUpdateByPrimaryKeySelectiveElementGenerated(element, introspectedTable);
} }
...@@ -315,16 +310,16 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin ...@@ -315,16 +310,16 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin
@Override @Override
public boolean sqlMapUpsertSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) { public boolean sqlMapUpsertSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {
// parameterType // parameterType
XmlElementGeneratorTools.replaceAttribute(element, new Attribute("parameterType", "map")); XmlElementTools.replaceAttribute(element, new Attribute("parameterType", "map"));
// 替换insert column // 替换insert column
XmlElementGeneratorTools.replaceXmlElement(insertColumnsEle, this.generateInsertColumnSelective(columns)); XmlElementTools.replaceXmlElement(insertColumnsEle, this.generateInsertColumnSelective(columns));
// 替换insert values // 替换insert values
XmlElementGeneratorTools.replaceXmlElement(insertValuesEle, this.generateInsertValuesSelective(columns)); XmlElementTools.replaceXmlElement(insertValuesEle, this.generateInsertValuesSelective(columns));
// 替换update set // 替换update set
XmlElementGeneratorTools.replaceXmlElement(setsEle, this.generateSetsSelective(columns)); XmlElementTools.replaceXmlElement(setsEle, this.generateSetsSelective(columns));
return true; return true;
} }
...@@ -343,13 +338,13 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin ...@@ -343,13 +338,13 @@ public class SelectiveEnhancedPlugin extends BasePlugin implements IUpsertPlugin
public boolean sqlMapUpsertByExampleSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) { public boolean sqlMapUpsertByExampleSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {
// 替换insert column // 替换insert column
XmlElementGeneratorTools.replaceXmlElement(insertColumnsEle, this.generateInsertColumnSelective(columns)); XmlElementTools.replaceXmlElement(insertColumnsEle, this.generateInsertColumnSelective(columns));
// 替换insert values // 替换insert values
XmlElementGeneratorTools.replaceXmlElement(insertValuesEle, this.generateInsertValuesSelective(columns, false)); XmlElementTools.replaceXmlElement(insertValuesEle, this.generateInsertValuesSelective(columns, false));
// 替换update set // 替换update set
XmlElementGeneratorTools.replaceXmlElement(setsEle, this.generateSetsSelective(columns)); XmlElementTools.replaceXmlElement(setsEle, this.generateSetsSelective(columns));
return true; return true;
} }
......
...@@ -28,7 +28,6 @@ import org.mybatis.generator.internal.util.StringUtility; ...@@ -28,7 +28,6 @@ import org.mybatis.generator.internal.util.StringUtility;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.List; import java.util.List;
/** /**
...@@ -77,9 +76,7 @@ public class BasePlugin extends PluginAdapter { ...@@ -77,9 +76,7 @@ public class BasePlugin extends PluginAdapter {
// 先执行一次生成CommentGenerator操作,然后再替换 // 先执行一次生成CommentGenerator操作,然后再替换
context.getCommentGenerator(); context.getCommentGenerator();
Field field = Context.class.getDeclaredField("commentGenerator"); BeanUtils.setProperty(context, "commentGenerator", templateCommentGenerator);
field.setAccessible(true);
field.set(context, templateCommentGenerator);
} catch (Exception e) { } catch (Exception e) {
logger.error("反射异常", e); logger.error("反射异常", e);
} }
......
/*
* Copyright (c) 2018.
*
* 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.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/5/3 18:39
* ---------------------------------------------------------------------------
*/
public class BeanUtils {
/**
* 设置属性
* @param bean
* @param name
* @param value
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public static void setProperty(final Object bean, final String name, final Object value) throws NoSuchFieldException, IllegalAccessException {
Field field = bean.getClass().getDeclaredField(name);
field.setAccessible(true);
field.set(bean, value);
}
/**
* 获取属性
* @param bean
* @param name
* @return
*/
public static Object getProperty(final Object bean, final String name) throws NoSuchFieldException, IllegalAccessException {
Field field = bean.getClass().getDeclaredField(name);
field.setAccessible(true);
return field.get(bean);
}
/**
* 执行无参方法
* @param bean
* @param name
* @return
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static Object invoke(final Object bean, final String name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = bean.getClass().getDeclaredMethod(name);
method.setAccessible(true);
return method.invoke(bean);
}
}
...@@ -16,14 +16,18 @@ ...@@ -16,14 +16,18 @@
package com.itfsw.mybatis.generator.plugins.utils; package com.itfsw.mybatis.generator.plugins.utils;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.InnerClass; import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.Interface; import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method; import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass; import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Element; 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.api.dom.xml.XmlElement;
import java.util.Iterator;
import java.util.List; import java.util.List;
/** /**
...@@ -37,80 +41,88 @@ import java.util.List; ...@@ -37,80 +41,88 @@ import java.util.List;
public class FormatTools { public class FormatTools {
/** /**
* 在最佳位置添加方法 * 在最佳位置添加方法
*
* @param innerClass * @param innerClass
* @param method * @param method
*/ */
public static void addMethodWithBestPosition(InnerClass innerClass, Method method){ public static void addMethodWithBestPosition(InnerClass innerClass, Method method) {
addMethodWithBestPosition(method, innerClass.getMethods()); addMethodWithBestPosition(method, innerClass.getMethods());
} }
/** /**
* 在最佳位置添加方法 * 在最佳位置添加方法
*
* @param interfacz * @param interfacz
* @param method * @param method
*/ */
public static void addMethodWithBestPosition(Interface interfacz, Method method){ public static void addMethodWithBestPosition(Interface interfacz, Method method) {
addMethodWithBestPosition(method, interfacz.getMethods()); addMethodWithBestPosition(method, interfacz.getMethods());
} }
/** /**
* 在最佳位置添加方法 * 在最佳位置添加方法
*
* @param topLevelClass * @param topLevelClass
* @param method * @param method
*/ */
public static void addMethodWithBestPosition(TopLevelClass topLevelClass, Method method){ public static void addMethodWithBestPosition(TopLevelClass topLevelClass, Method method) {
addMethodWithBestPosition(method, topLevelClass.getMethods()); addMethodWithBestPosition(method, topLevelClass.getMethods());
} }
/** /**
* 在最佳位置添加节点 * 在最佳位置添加节点
*
* @param rootElement * @param rootElement
* @param element * @param element
*/ */
public static void addElementWithBestPosition(XmlElement rootElement, XmlElement element){ public static void addElementWithBestPosition(XmlElement rootElement, XmlElement element) {
String id = getIdFromElement(element); // sql 元素都放在sql后面
if (id == null){ if (element.getName().equals("sql")) {
rootElement.addElement(element); int index = 0;
for (Element ele : rootElement.getElements()) {
if (ele instanceof XmlElement && ((XmlElement) ele).getName().equals("sql")) {
index++;
}
}
rootElement.addElement(index, element);
} else { } else {
List<Element> elements = rootElement.getElements();
int index = -1; // 根据id 排序
for (int i = 0; i < elements.size(); i++){ String id = getIdFromElement(element);
Element ele = elements.get(i); if (id == null) {
if (ele instanceof XmlElement){ rootElement.addElement(element);
String eleId = getIdFromElement((XmlElement) ele); } else {
if (eleId != null){ List<Element> elements = rootElement.getElements();
if (eleId.startsWith(id)){ int index = -1;
if (index == - 1){ for (int i = 0; i < elements.size(); i++) {
index = i; Element ele = elements.get(i);
if (ele instanceof XmlElement) {
String eleId = getIdFromElement((XmlElement) ele);
if (eleId != null) {
if (eleId.startsWith(id)) {
if (index == -1) {
index = i;
}
} else if (id.startsWith(eleId)) {
index = i + 1;
} }
} else if (id.startsWith(eleId)){
index = i + 1;
} }
} }
} }
}
if (index == -1 || index >= elements.size()){ if (index == -1 || index >= elements.size()) {
rootElement.addElement(element); rootElement.addElement(element);
} else { } else {
elements.add(index, element); elements.add(index, element);
}
} }
} }
} }
/** /**
* 找出节点ID值 * 找出节点ID值
*
* @param element * @param element
* @return * @return
*/ */
private static String getIdFromElement(XmlElement element){ private static String getIdFromElement(XmlElement element) {
for (Attribute attribute : element.getAttributes()){ for (Attribute attribute : element.getAttributes()) {
if (attribute.getName().equals("id")){ if (attribute.getName().equals("id")) {
return attribute.getValue(); return attribute.getValue();
} }
} }
...@@ -119,33 +131,74 @@ public class FormatTools { ...@@ -119,33 +131,74 @@ public class FormatTools {
/** /**
* 获取最佳添加位置 * 获取最佳添加位置
*
* @param method * @param method
* @param methods * @param methods
* @return * @return
*/ */
private static void addMethodWithBestPosition(Method method, List<Method> methods){ private static void addMethodWithBestPosition(Method method, List<Method> methods) {
int index = -1; int index = -1;
for (int i = 0; i < methods.size(); i++){ for (int i = 0; i < methods.size(); i++) {
Method m = methods.get(i); Method m = methods.get(i);
if (m.getName().equals(method.getName())){ if (m.getName().equals(method.getName())) {
if (m.getParameters().size() <= method.getParameters().size()){ if (m.getParameters().size() <= method.getParameters().size()) {
index = i + 1; index = i + 1;
} else { } else {
index = i; index = i;
} }
} else if (m.getName().startsWith(method.getName())){ } else if (m.getName().startsWith(method.getName())) {
if (index == - 1){ if (index == -1) {
index = i; index = i;
} }
} else if (method.getName().startsWith(m.getName())){ } else if (method.getName().startsWith(m.getName())) {
index = i + 1; index = i + 1;
} }
} }
if (index == -1 || index >= methods.size()){ if (index == -1 || index >= methods.size()) {
methods.add(methods.size(), method); methods.add(methods.size(), method);
} else { } else {
methods.add(index, method); methods.add(index, method);
} }
} }
/**
* 替换已有方法注释
* @param commentGenerator
* @param method
* @param introspectedTable
*/
public static void replaceGeneralMethodComment(CommentGenerator commentGenerator, Method method, IntrospectedTable introspectedTable) {
method.getJavaDocLines().clear();
commentGenerator.addGeneralMethodComment(method, introspectedTable);
}
/**
* 替换已有注释
* @param commentGenerator
* @param element
*/
public static void replaceComment(CommentGenerator commentGenerator, XmlElement element) {
Iterator<Element> elementIterator = element.getElements().iterator();
boolean flag = false;
while (elementIterator.hasNext()) {
Element ele = elementIterator.next();
if (ele instanceof TextElement && ((TextElement) ele).getContent().matches("<!--")) {
flag = true;
}
if (flag) {
elementIterator.remove();
}
if (ele instanceof TextElement && ((TextElement) ele).getContent().matches("-->")) {
flag = false;
}
}
XmlElement tmpEle = new XmlElement("tmp");
commentGenerator.addComment(tmpEle);
for (int i = tmpEle.getElements().size() - 1; i >= 0; i--) {
element.addElement(0, tmpEle.getElements().get(i));
}
}
} }
...@@ -17,7 +17,6 @@ ...@@ -17,7 +17,6 @@
package com.itfsw.mybatis.generator.plugins.utils; package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.ExampleTargetPlugin; import com.itfsw.mybatis.generator.plugins.ExampleTargetPlugin;
import org.mybatis.generator.api.FullyQualifiedTable;
import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.config.Context; import org.mybatis.generator.config.Context;
...@@ -25,9 +24,7 @@ import org.mybatis.generator.config.JavaModelGeneratorConfiguration; ...@@ -25,9 +24,7 @@ import org.mybatis.generator.config.JavaModelGeneratorConfiguration;
import org.mybatis.generator.config.PluginConfiguration; import org.mybatis.generator.config.PluginConfiguration;
import org.mybatis.generator.internal.util.StringUtility; import org.mybatis.generator.internal.util.StringUtility;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/** /**
* --------------------------------------------------------------------------- * ---------------------------------------------------------------------------
...@@ -52,22 +49,12 @@ public class IntrospectedTableTools { ...@@ -52,22 +49,12 @@ public class IntrospectedTableTools {
introspectedTable.getTableConfiguration().setDomainObjectName(domainObjectName); introspectedTable.getTableConfiguration().setDomainObjectName(domainObjectName);
// FullyQualifiedTable修正 // FullyQualifiedTable修正
Field domainObjectNameField = FullyQualifiedTable.class.getDeclaredField("domainObjectName"); BeanUtils.setProperty(introspectedTable.getFullyQualifiedTable(), "domainObjectName", domainObjectName);
domainObjectNameField.setAccessible(true);
domainObjectNameField.set(introspectedTable.getFullyQualifiedTable(), domainObjectName);
// 重新修正introspectedTable属性信息 // 重新修正introspectedTable属性信息
Method calculateJavaClientAttributes = IntrospectedTable.class.getDeclaredMethod("calculateJavaClientAttributes"); BeanUtils.invoke(introspectedTable, "calculateJavaClientAttributes");
calculateJavaClientAttributes.setAccessible(true); BeanUtils.invoke(introspectedTable, "calculateModelAttributes");
calculateJavaClientAttributes.invoke(introspectedTable); BeanUtils.invoke(introspectedTable, "calculateXmlAttributes");
Method calculateModelAttributes = IntrospectedTable.class.getDeclaredMethod("calculateModelAttributes");
calculateModelAttributes.setAccessible(true);
calculateModelAttributes.invoke(introspectedTable);
Method calculateXmlAttributes = IntrospectedTable.class.getDeclaredMethod("calculateXmlAttributes");
calculateXmlAttributes.setAccessible(true);
calculateXmlAttributes.invoke(introspectedTable);
// 注意!! 如果配置了ExampleTargetPlugin插件,要修正Example 位置 // 注意!! 如果配置了ExampleTargetPlugin插件,要修正Example 位置
PluginConfiguration configuration = PluginTools.getPluginConfiguration(context, ExampleTargetPlugin.class); PluginConfiguration configuration = PluginTools.getPluginConfiguration(context, ExampleTargetPlugin.class);
......
...@@ -163,28 +163,4 @@ public class JavaElementGeneratorTools { ...@@ -163,28 +163,4 @@ public class JavaElementGeneratorTools {
} }
return type; return type;
} }
/**
* 克隆方法
* @param method
*/
public static Method cloneMethod(Method method) {
Method result = new Method();
result.setConstructor(method.isConstructor());
result.setFinal(method.isFinal());
result.setName(method.getName());
result.setNative(method.isNative());
result.setReturnType(method.getReturnType());
result.setSynchronized(method.isSynchronized());
result.setStatic(method.isStatic());
result.setVisibility(method.getVisibility());
for (Parameter parameter : method.getParameters()) {
result.addParameter(parameter);
}
for (String docLine : method.getJavaDocLines()){
result.addJavaDocLine(docLine);
}
result.addBodyLines(method.getBodyLines());
return result;
}
} }
...@@ -22,7 +22,6 @@ import org.mybatis.generator.config.PluginConfiguration; ...@@ -22,7 +22,6 @@ import org.mybatis.generator.config.PluginConfiguration;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
...@@ -83,9 +82,7 @@ public class PluginTools { ...@@ -83,9 +82,7 @@ public class PluginTools {
public static List<PluginConfiguration> getConfigPlugins(Context ctx) { public static List<PluginConfiguration> getConfigPlugins(Context ctx) {
try { try {
// 利用反射获取pluginConfigurations属性 // 利用反射获取pluginConfigurations属性
Field field = Context.class.getDeclaredField("pluginConfigurations"); return (List<PluginConfiguration>) BeanUtils.getProperty(ctx, "pluginConfigurations");
field.setAccessible(true);
return (List<PluginConfiguration>) field.get(ctx);
} catch (Exception e) { } catch (Exception e) {
logger.error("插件检查反射异常", e); logger.error("插件检查反射异常", e);
} }
......
...@@ -134,44 +134,6 @@ public class XmlElementGeneratorTools { ...@@ -134,44 +134,6 @@ public class XmlElementGeneratorTools {
} }
} }
/**
* 移除属性
* @param element
* @param name
*/
public static void removeAttribute(XmlElement element, String name) {
Iterator<Attribute> iterator = element.getAttributes().iterator();
while (iterator.hasNext()) {
Attribute attribute = iterator.next();
if (attribute.getName().equals(name)) {
iterator.remove();
}
}
}
/**
* 替换属性
* @param element
* @param attribute
*/
public static void replaceAttribute(XmlElement element, Attribute attribute) {
removeAttribute(element, attribute.getName());
element.addAttribute(attribute);
}
/**
* xmlElement 替换
* @param srcEle
* @param destEle
*/
public static void replaceXmlElement(XmlElement srcEle, XmlElement destEle) {
srcEle.setName(destEle.getName());
srcEle.getAttributes().clear();
srcEle.getAttributes().addAll(destEle.getAttributes());
srcEle.getElements().clear();
srcEle.getElements().addAll(destEle.getElements());
}
/** /**
* 生成keys Ele * 生成keys Ele
* @param columns * @param columns
...@@ -517,26 +479,6 @@ public class XmlElementGeneratorTools { ...@@ -517,26 +479,6 @@ public class XmlElementGeneratorTools {
} }
} }
/**
* 查找指定xml节点下指定节点名称的元素
* @param xmlElement
* @param name
* @return
*/
public static List<XmlElement> findXmlElements(XmlElement xmlElement, String name) {
List<XmlElement> list = new ArrayList<>();
List<Element> elements = xmlElement.getElements();
for (Element ele : elements) {
if (ele instanceof XmlElement) {
XmlElement xmlElement1 = (XmlElement) ele;
if (name.equalsIgnoreCase(xmlElement1.getName())) {
list.add(xmlElement1);
}
}
}
return list;
}
/** /**
* 生成 xxxByPrimaryKey 的where 语句 * 生成 xxxByPrimaryKey 的where 语句
* @param element * @param element
......
/*
* Copyright (c) 2018.
*
* 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.utils;
import org.mybatis.generator.api.dom.xml.Attribute;
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 java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/5/2 17:52
* ---------------------------------------------------------------------------
*/
public class XmlElementTools {
/**
* 获取属性
* @param element
* @param name
*/
public static Attribute getAttribute(XmlElement element, String name) {
Iterator<Attribute> iterator = element.getAttributes().iterator();
while (iterator.hasNext()) {
Attribute attribute = iterator.next();
if (attribute.getName().equals(name)) {
return attribute;
}
}
return null;
}
/**
* 移除属性
* @param element
* @param name
*/
public static void removeAttribute(XmlElement element, String name) {
Iterator<Attribute> iterator = element.getAttributes().iterator();
while (iterator.hasNext()) {
Attribute attribute = iterator.next();
if (attribute.getName().equals(name)) {
iterator.remove();
}
}
}
/**
* 替换属性
* @param element
* @param attribute
*/
public static void replaceAttribute(XmlElement element, Attribute attribute) {
removeAttribute(element, attribute.getName());
element.addAttribute(attribute);
}
/**
* xmlElement 替换
* @param srcEle
* @param destEle
*/
public static void replaceXmlElement(XmlElement srcEle, XmlElement destEle) {
srcEle.setName(destEle.getName());
srcEle.getAttributes().clear();
srcEle.getAttributes().addAll(destEle.getAttributes());
srcEle.getElements().clear();
srcEle.getElements().addAll(destEle.getElements());
}
/**
* 查找指定xml节点下指定节点名称的元素
* @param xmlElement
* @param name
* @return
*/
public static List<XmlElement> findXmlElements(XmlElement xmlElement, String name) {
List<XmlElement> list = new ArrayList<>();
List<Element> elements = xmlElement.getElements();
for (Element ele : elements) {
if (ele instanceof XmlElement) {
XmlElement xmlElement1 = (XmlElement) ele;
if (name.equalsIgnoreCase(xmlElement1.getName())) {
list.add(xmlElement1);
}
}
}
return list;
}
/**
* 查询指定xml下所有text xml 节点
* @param xmlElement
* @return
*/
public static List<TextElement> findAllTextElements(XmlElement xmlElement){
List<TextElement> textElements = new ArrayList<>();
for (Element element : xmlElement.getElements()){
if (element instanceof XmlElement){
textElements.addAll(findAllTextElements((XmlElement) element));
} else if (element instanceof TextElement){
textElements.add((TextElement) element);
}
}
return textElements;
}
/**
* 拷贝
* @param element
* @return
*/
public static XmlElement clone(XmlElement element) {
XmlElement destEle = new XmlElement(element.getName());
for (Attribute attribute : element.getAttributes()) {
destEle.addAttribute(XmlElementTools.clone(attribute));
}
for (Element ele : element.getElements()) {
if (ele instanceof XmlElement) {
destEle.addElement(XmlElementTools.clone((XmlElement) ele));
} else if (ele instanceof TextElement) {
destEle.addElement(XmlElementTools.clone((TextElement) ele));
}
}
return destEle;
}
/**
* 拷贝
* @param attribute
* @return
*/
public static Attribute clone(Attribute attribute) {
return new Attribute(attribute.getName(), attribute.getValue());
}
/**
* 拷贝
* @param textElement
* @return
*/
public static TextElement clone(TextElement textElement) {
return new TextElement(textElement.getContent());
}
}
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package com.itfsw.mybatis.generator.plugins.utils.enhanced; package com.itfsw.mybatis.generator.plugins.utils.enhanced;
import com.itfsw.mybatis.generator.plugins.utils.BeanUtils;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -40,10 +41,9 @@ public class InnerTypeFullyQualifiedJavaType extends FullyQualifiedJavaType { ...@@ -40,10 +41,9 @@ public class InnerTypeFullyQualifiedJavaType extends FullyQualifiedJavaType {
try{ try{
// 修正package // 修正package
java.lang.reflect.Field packageName = this.getClass().getSuperclass().getDeclaredField("packageName");
packageName.setAccessible(true);
String oldPackageName = getPackageName(); String oldPackageName = getPackageName();
packageName.set(this, oldPackageName.substring(0, oldPackageName.lastIndexOf(".")));
BeanUtils.setProperty(this, "packageName", oldPackageName.substring(0, oldPackageName.lastIndexOf(".")));
outerType = oldPackageName.substring(oldPackageName.lastIndexOf(".") + 1); outerType = oldPackageName.substring(oldPackageName.lastIndexOf(".") + 1);
} catch (Exception e){ } catch (Exception e){
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
package com.itfsw.mybatis.generator.plugins.utils.hook; package com.itfsw.mybatis.generator.plugins.utils.hook;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin; import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.BeanUtils;
import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable; import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin; import org.mybatis.generator.api.Plugin;
...@@ -80,9 +81,7 @@ public class HookAggregator implements IUpsertPluginHook, IModelBuilderPluginHoo ...@@ -80,9 +81,7 @@ public class HookAggregator implements IUpsertPluginHook, IModelBuilderPluginHoo
List list = new ArrayList(); List list = new ArrayList();
// 反射获取插件列表,不能用单例去弄,不然因为类释放的问题而导致测试用例出问题 // 反射获取插件列表,不能用单例去弄,不然因为类释放的问题而导致测试用例出问题
try { try {
java.lang.reflect.Field field = this.context.getPlugins().getClass().getDeclaredField("plugins"); List<Plugin> plugins = (List<Plugin>) BeanUtils.getProperty(this.context.getPlugins(), "plugins");
field.setAccessible(true);
List<Plugin> plugins = (List<Plugin>) field.get(this.context.getPlugins());
for (Plugin plugin : plugins) { for (Plugin plugin : plugins) {
if (clazz.isInstance(plugin)) { if (clazz.isInstance(plugin)) {
list.add(plugin); list.add(plugin);
......
/*
* Copyright (c) 2018.
*
* 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.io.IOException;
import java.sql.SQLException;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/5/2 17:05
* ---------------------------------------------------------------------------
*/
public class OptimisticLockerPluginTest {
/**
* 初始化数据库
*/
@BeforeClass
public static void init() throws SQLException, IOException, ClassNotFoundException {
DBHelper.createDB("scripts/OptimisticLockerPlugin/init.sql");
}
/**
* 测试 updateWithVersionByExampleSelective
*/
@Test
public void testUpdateWithVersionByExampleSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/OptimisticLockerPlugin/mybatis-generator.xml");
tool.generate(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", 1l);
ObjectUtil orCriteria = new ObjectUtil(tbExample.invoke("or"));
orCriteria.invoke("andField1EqualTo", "ts1");
// sql
String sql = SqlHelper.getFormatMapperSql(tbMapper.getObject(), "deleteWithVersionByExample", 1L, tbExample.getObject());
Assert.assertEquals(sql, "update tb SET field_1 = 'null' , inc_f2 = 5 WHERE ( id = '1' )");
}
});
}
}
\ No newline at end of file
/*
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 COMMENT '注释1',
`field1` varchar(255) DEFAULT NULL COMMENT '注释2',
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
`inc_f2` bigint(20) DEFAULT '0',
`inc_f3` bigint(20) 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');
-- ----------------------------
-- Table structure for tb_key_word
-- ----------------------------
DROP TABLE IF EXISTS `tb_key_word`;
CREATE TABLE `tb_key_word` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '注释1',
`field2` int(11) DEFAULT NULL,
`inc_f1` bigint(20) NOT NULL DEFAULT '0',
`update` bigint(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of tb_key_word
-- ----------------------------
INSERT INTO `tb_key_word` VALUES ('1', '0', '0', '1');
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2018.
~
~ 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.OptimisticLockerPlugin" />
<!--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="versionColumn" value="inc_f1"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb_keys">
<property name="versionColumn" value="inc_f1"/>
</table>
<table tableName="tb_blobs">
<property name="versionColumn" value="inc_f1"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment