Commit b3e4792e authored by hewei's avatar hewei

优化修正

parent e686bc63
......@@ -60,7 +60,7 @@ public class BatchInsertPlugin extends BasePlugin {
// 插件使用前提是使用了ModelColumnPlugin插件
if (!PluginTools.checkDependencyPlugin(ModelColumnPlugin.class, getContext())) {
if (!PluginTools.checkDependencyPlugin(getContext(), ModelColumnPlugin.class)) {
logger.error("itfsw:插件" + this.getClass().getTypeName() + "插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!");
return false;
}
......
/*
* 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.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.PluginTools;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* 增量插件
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/19 15:20
* ---------------------------------------------------------------------------
*/
public class IncrementsPlugin extends BasePlugin {
public static final String PRE_INCREMENTS_COLUMNS = "incrementsColumns"; // incrementsColumns property
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是使用了ModelBuilderPlugin插件
if (!PluginTools.checkDependencyPlugin(getContext(), ModelBuilderPlugin.class)) {
logger.error("itfsw:插件" + this.getClass().getTypeName() + "插件需配合com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin插件使用!");
return false;
}
return super.validate(warnings);
}
}
......@@ -18,10 +18,13 @@ package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.PluginTools;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.JavaElementEnhanced;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.internal.util.JavaBeansUtil;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.List;
......@@ -35,6 +38,18 @@ import java.util.List;
*/
public class ModelBuilderPlugin extends BasePlugin {
public static final String BUILDER_CLASS_NAME = "Builder"; // Builder 类名
private FullyQualifiedJavaType inc; // 是否支持Increments
/**
* 初始化阶段
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
* @param introspectedTable
* @return
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
this.inc = null;
}
/**
* Model Methods 生成
......@@ -47,7 +62,7 @@ public class ModelBuilderPlugin extends BasePlugin {
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// 判断是否有生成Model的WithBLOBs类
List<IntrospectedColumn> columns = introspectedTable.getRules().generateRecordWithBLOBsClass() ? introspectedTable.getNonBLOBColumns() : introspectedTable.getAllColumns();
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, columns);
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, columns, true);
topLevelClass.addInnerClass(innerClass);
return true;
}
......@@ -61,20 +76,20 @@ public class ModelBuilderPlugin extends BasePlugin {
*/
@Override
public boolean modelRecordWithBLOBsClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, introspectedTable.getAllColumns());
InnerClass innerClass = this.generateModelBuilder(topLevelClass, introspectedTable, introspectedTable.getAllColumns(), false);
topLevelClass.addInnerClass(innerClass);
return true;
}
/**
* 生成ModelBuilder
*
* @param topLevelClass
* @param introspectedTable
* @param columns
* @param modelBaseRecord
* @return
*/
private InnerClass generateModelBuilder(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, List<IntrospectedColumn> columns){
private InnerClass generateModelBuilder(TopLevelClass topLevelClass, IntrospectedTable introspectedTable, List<IntrospectedColumn> columns, boolean modelBaseRecord) {
// 生成内部Builder类
InnerClass innerClass = new InnerClass(BUILDER_CLASS_NAME);
innerClass.setVisibility(JavaVisibility.PUBLIC);
......@@ -127,6 +142,71 @@ public class ModelBuilderPlugin extends BasePlugin {
logger.debug("itfsw(数据Model链式构建插件):" + topLevelClass.getType().getShortName() + ".Builder增加build方法。");
// ========================================== IncrementsPlugin =======================================
if (PluginTools.getPluginConfiguration(context, IncrementsPlugin.class) != null) {
String incrementsColumns = introspectedTable.getTableConfigurationProperty(IncrementsPlugin.PRE_INCREMENTS_COLUMNS);
if (StringUtility.stringHasValue(incrementsColumns)) {
if (modelBaseRecord) {
this.inc = new FullyQualifiedJavaType(topLevelClass.getType().getShortName() + "." + BUILDER_CLASS_NAME + ".Inc");
// 增加枚举
InnerEnum eIncrements = new InnerEnum(new FullyQualifiedJavaType("Inc"));
eIncrements.setVisibility(JavaVisibility.PUBLIC);
eIncrements.setStatic(true);
eIncrements.addEnumConstant("INC,DEC");
commentGenerator.addEnumComment(eIncrements, introspectedTable);
innerClass.addInnerEnum(eIncrements);
// 增加field
Field fIncrements = JavaElementGeneratorTools.generateField(
"incs",
JavaVisibility.PROTECTED,
new FullyQualifiedJavaType("Map<String, " + this.inc.getFullyQualifiedName() + ">"),
"new HashMap<String, " + this.inc.getFullyQualifiedName() + ">()"
);
commentGenerator.addFieldComment(fIncrements, introspectedTable);
topLevelClass.addField(fIncrements);
topLevelClass.addImportedType("java.util.Map");
topLevelClass.addImportedType("java.util.HashMap");
// getter&setter
Method mGetter = JavaElementGeneratorTools.generateGetterMethod(fIncrements);
commentGenerator.addGetterComment(mGetter, introspectedTable, null);
topLevelClass.addMethod(mGetter);
Method mSetter = JavaElementGeneratorTools.generateSetterMethod(fIncrements);
commentGenerator.addSetterComment(mSetter, introspectedTable, null);
topLevelClass.addMethod(mSetter);
}
// 切分
String[] incrementsColumnsStrs = incrementsColumns.split(",");
for (String incrementsColumnsStr : incrementsColumnsStrs) {
IntrospectedColumn column = introspectedTable.getColumn(incrementsColumnsStr);
if (column == null) {
logger.warn("itfsw:插件" + IncrementsPlugin.class.getTypeName() + "插件没有找到column为" + incrementsColumnsStr + "的字段!");
} else if (columns.indexOf(column) != -1) {
Field field = JavaBeansUtil.getJavaBeansField(column, context, introspectedTable);
// 增加方法
Method mIncrements = JavaElementGeneratorTools.generateMethod(
field.getName(),
JavaVisibility.PUBLIC,
innerClass.getType(),
new Parameter(field.getType(), field.getName()),
new Parameter(this.inc, "inc")
);
commentGenerator.addSetterComment(mIncrements, introspectedTable, column);
Method setterMethod = JavaBeansUtil.getJavaBeansSetter(column, context, introspectedTable);
mIncrements.addBodyLine("obj.incs.put(\"" + column.getActualColumnName() + "\", inc);");
mIncrements.addBodyLine("obj." + setterMethod.getName() + "(" + field.getName() + ");");
mIncrements.addBodyLine("return this;");
JavaElementEnhanced.addMethodWithBestPosition(innerClass, mIncrements);
}
}
}
}
return innerClass;
}
}
......@@ -46,15 +46,13 @@ public class SelectiveEnhancedPlugin extends BasePlugin {
public boolean validate(List<String> warnings) {
// 插件使用前提是使用了ModelColumnPlugin插件
if (!PluginTools.checkDependencyPlugin(ModelColumnPlugin.class, getContext())) {
if (!PluginTools.checkDependencyPlugin(getContext(), ModelColumnPlugin.class)) {
logger.error("itfsw:插件" + this.getClass().getTypeName() + "插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!");
return false;
}
// 插件配置位置最好是在末尾
if (PluginTools.getConfigPlugins(getContext()).size() - 1 != PluginTools.getPluginIndex(SelectiveEnhancedPlugin.class, getContext())){
logger.warn("itfsw:插件" + this.getClass().getTypeName() + "插件建议配置在所有插件末尾以便最后调用,否则某些Selective方法得不到增强!");
}
// 插件位置
PluginTools.shouldAfterPlugins(getContext(), this.getClass(), UpsertPlugin.class);
return super.validate(warnings);
}
......
......@@ -53,7 +53,7 @@ public class BasePlugin extends PluginAdapter {
super.setContext(context);
// 配置插件使用的模板引擎
PluginConfiguration cfg = PluginTools.getPluginConfiguration(CommentPlugin.class, context);
PluginConfiguration cfg = PluginTools.getPluginConfiguration(context, CommentPlugin.class);
if (cfg == null || cfg.getProperty(CommentPlugin.PRE_TEMPLATE) == null){
if (context.getCommentGenerator() instanceof DefaultCommentGenerator){
......
......@@ -67,7 +67,7 @@ public class IntrospectedTableTools {
calculateXmlAttributes.invoke(introspectedTable);
// 注意!! 如果配置了ExampleTargetPlugin插件,要修正Example 位置
PluginConfiguration configuration = PluginTools.getPluginConfiguration(ExampleTargetPlugin.class, context);
PluginConfiguration configuration = PluginTools.getPluginConfiguration(context, ExampleTargetPlugin.class);
if (configuration != null && configuration.getProperty(ExampleTargetPlugin.TARGET_PACKAGE_KEY) != null){
String exampleType = introspectedTable.getExampleType();
// 修改包名
......
......@@ -38,23 +38,25 @@ public class PluginTools {
/**
* 检查插件依赖
*
* @param context 上下文
* @param plugin 插件
* @param ctx 上下文
* @return
*/
public static boolean checkDependencyPlugin(Class plugin, Context ctx) {
return getPluginIndex(plugin, ctx) >= 0;
public static boolean checkDependencyPlugin(Context context, Class plugin) {
return getPluginIndex(context, plugin) >= 0;
}
/**
* 获取插件所在位置
*
* @param context 上下文
* @param plugin 插件
* @param ctx 上下文
*
* @return -1:未找到
*/
public static int getPluginIndex(Class plugin, Context ctx) {
List<PluginConfiguration> list = getConfigPlugins(ctx);
public static int getPluginIndex(Context context, Class plugin) {
List<PluginConfiguration> list = getConfigPlugins(context);
// 检查是否配置了ModelColumnPlugin插件
for (int i = 0; i < list.size(); i++) {
PluginConfiguration config = list.get(i);
......@@ -85,15 +87,38 @@ public class PluginTools {
/**
* 获取插件配置
*
* @param context 上下文
* @param plugin 插件
* @param ctx 上下文
* @return
*/
public static PluginConfiguration getPluginConfiguration(Class plugin, Context ctx){
int index = getPluginIndex(plugin, ctx);
public static PluginConfiguration getPluginConfiguration(Context context, Class plugin){
int index = getPluginIndex(context, plugin);
if (index > -1){
return getConfigPlugins(ctx).get(index);
return getConfigPlugins(context).get(index);
}
return null;
}
/**
* 插件位置需要配置在某些插件后面
*
* @param context
* @param plugin
* @param plugins
* @return
*/
public static boolean shouldAfterPlugins(Context context, Class plugin, Class ... plugins){
int index = getPluginIndex(context, plugin);
if (plugins != null){
for (Class cls : plugins){
int index1 = getPluginIndex(context, cls);
if (index1 != -1 && index1 >= index){
logger.warn("itfsw:插件" + plugin.getTypeName() + "插件建议配置在插件"+cls.getTypeName()+"后面,否则某些功能可能得不到增强!");
return false;
}
}
return true;
}
return false;
}
}
/*
* 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.utils.enhanced;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.Method;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* JavaElement 增强
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/6/19 16:34
* ---------------------------------------------------------------------------
*/
public class JavaElementEnhanced {
/**
* 在最佳位置添加方法
*
* @param innerClass
* @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 == -1){
index = i;
}
}
}
if (index == -1){
innerClass.addMethod(method);
} else {
methods.add(index, method);
}
}
}
......@@ -77,7 +77,7 @@ public class TemplateCommentGenerator implements CommentGenerator {
for (EnumNode node : EnumNode.values()){
Element element = doc.getRootElement().elementByID(node.value());
if (element != null){
Configuration cfg = new Configuration();
Configuration cfg = new Configuration(Configuration.VERSION_2_3_26);
// 字符串清理
Template template = new Template(node.value(), element.getText(), cfg);
templates.put(node, template);
......
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