Commit c33616c4 authored by hewei's avatar hewei

重构代码插件依赖关系

parent cbfe10c9
/*
* 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.utils.BasePlugin;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* 乐观锁插件
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/4/26 10:24
* ---------------------------------------------------------------------------
*/
public class OptimisticLockerPlugin extends BasePlugin {
@Override
public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
return super.contextGenerateAdditionalJavaFiles(introspectedTable);
}
}
...@@ -18,6 +18,7 @@ package com.itfsw.mybatis.generator.plugins.utils; ...@@ -18,6 +18,7 @@ package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.CommentPlugin; import com.itfsw.mybatis.generator.plugins.CommentPlugin;
import com.itfsw.mybatis.generator.plugins.utils.enhanced.TemplateCommentGenerator; import com.itfsw.mybatis.generator.plugins.utils.enhanced.TemplateCommentGenerator;
import com.itfsw.mybatis.generator.plugins.utils.hook.HookAggregator;
import org.mybatis.generator.api.CommentGenerator; import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.PluginAdapter; import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.config.Context; import org.mybatis.generator.config.Context;
...@@ -45,19 +46,20 @@ public class BasePlugin extends PluginAdapter { ...@@ -45,19 +46,20 @@ public class BasePlugin extends PluginAdapter {
/** /**
* Set the context under which this plugin is running. * Set the context under which this plugin is running.
* * @param context the new context
* @param context
* the new context
*/ */
@Override @Override
public void setContext(Context context) { public void setContext(Context context) {
super.setContext(context); super.setContext(context);
// 添加插件
HookAggregator.getInstance().setContext(context);
// 配置插件使用的模板引擎 // 配置插件使用的模板引擎
PluginConfiguration cfg = PluginTools.getPluginConfiguration(context, CommentPlugin.class); PluginConfiguration cfg = PluginTools.getPluginConfiguration(context, CommentPlugin.class);
if (cfg == null || cfg.getProperty(CommentPlugin.PRO_TEMPLATE) == null){ if (cfg == null || cfg.getProperty(CommentPlugin.PRO_TEMPLATE) == null) {
if (context.getCommentGenerator() instanceof DefaultCommentGenerator){ if (context.getCommentGenerator() instanceof DefaultCommentGenerator) {
// 使用默认模板引擎 // 使用默认模板引擎
commentGenerator = new TemplateCommentGenerator("default-comment.ftl", true); commentGenerator = new TemplateCommentGenerator("default-comment.ftl", true);
} else { } else {
...@@ -79,7 +81,7 @@ public class BasePlugin extends PluginAdapter { ...@@ -79,7 +81,7 @@ public class BasePlugin extends PluginAdapter {
field.setAccessible(true); field.setAccessible(true);
field.set(context, templateCommentGenerator); field.set(context, templateCommentGenerator);
} catch (Exception e) { } catch (Exception e) {
logger.error("反射异常",e); logger.error("反射异常", e);
} }
} }
} }
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package com.itfsw.mybatis.generator.plugins.utils; package com.itfsw.mybatis.generator.plugins.utils;
import com.itfsw.mybatis.generator.plugins.utils.hook.HookAggregator;
import org.mybatis.generator.config.Context; import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.PluginConfiguration; import org.mybatis.generator.config.PluginConfiguration;
import org.slf4j.Logger; import org.slf4j.Logger;
...@@ -36,6 +37,16 @@ import java.util.List; ...@@ -36,6 +37,16 @@ import java.util.List;
public class PluginTools { public class PluginTools {
private static final Logger logger = LoggerFactory.getLogger(PluginTools.class); private static final Logger logger = LoggerFactory.getLogger(PluginTools.class);
/**
* 获取挂载
* @param clazz
* @param <T>
* @return
*/
public static <T> T getHook(Class<T> clazz){
return (T) HookAggregator.getInstance();
}
/** /**
* 检查插件依赖 * 检查插件依赖
* *
......
...@@ -132,6 +132,58 @@ public class XmlElementGeneratorTools { ...@@ -132,6 +132,58 @@ public class XmlElementGeneratorTools {
} }
} }
/**
* 移除 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
* @param element
* @param introspectedTable
*/
public static void removeUseGeneratedKeys(XmlElement element, IntrospectedTable introspectedTable) {
GeneratedKey gk = introspectedTable.getGeneratedKey();
if (gk != null) {
removeAttribute(element, "useGeneratedKeys");
removeAttribute(element, "keyProperty");
removeAttribute(element, "keyColumn");
}
}
/**
* 移除属性
* @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
...@@ -156,7 +208,7 @@ public class XmlElementGeneratorTools { ...@@ -156,7 +208,7 @@ public class XmlElementGeneratorTools {
* @param columns * @param columns
* @return * @return
*/ */
public static Element generateKeysSelective(List<IntrospectedColumn> columns) { public static XmlElement generateKeysSelective(List<IntrospectedColumn> columns) {
return generateKeysSelective(columns, null); return generateKeysSelective(columns, null);
} }
...@@ -166,7 +218,7 @@ public class XmlElementGeneratorTools { ...@@ -166,7 +218,7 @@ public class XmlElementGeneratorTools {
* @param prefix * @param prefix
* @return * @return
*/ */
public static Element generateKeysSelective(List<IntrospectedColumn> columns, String prefix) { public static XmlElement generateKeysSelective(List<IntrospectedColumn> columns, String prefix) {
return generateKeysSelective(columns, prefix, true); return generateKeysSelective(columns, prefix, true);
} }
...@@ -216,7 +268,7 @@ public class XmlElementGeneratorTools { ...@@ -216,7 +268,7 @@ public class XmlElementGeneratorTools {
* @param columns * @param columns
* @return * @return
*/ */
public static Element generateValuesSelective(List<IntrospectedColumn> columns) { public static XmlElement generateValuesSelective(List<IntrospectedColumn> columns) {
return generateValuesSelective(columns, null); return generateValuesSelective(columns, null);
} }
...@@ -226,7 +278,7 @@ public class XmlElementGeneratorTools { ...@@ -226,7 +278,7 @@ public class XmlElementGeneratorTools {
* @param prefix * @param prefix
* @return * @return
*/ */
public static Element generateValuesSelective(List<IntrospectedColumn> columns, String prefix) { public static XmlElement generateValuesSelective(List<IntrospectedColumn> columns, String prefix) {
return generateValuesSelective(columns, prefix, true); return generateValuesSelective(columns, prefix, true);
} }
......
/*
* 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.hook;
import com.itfsw.mybatis.generator.plugins.utils.BasePlugin;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.Plugin;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/4/27 11:33
* ---------------------------------------------------------------------------
*/
public class HookAggregator implements IUpsertPluginHook {
protected static final Logger logger = LoggerFactory.getLogger(BasePlugin.class); // 日志
private final static HookAggregator instance = new HookAggregator();
private Context context;
/**
* constructor
*/
public HookAggregator() {
}
/**
* Getter method for property <tt>instance</tt>.
* @return property value of instance
* @author hewei
*/
public static HookAggregator getInstance() {
return instance;
}
/**
* Setter method for property <tt>context</tt>.
* @param context value to be assigned to property context
* @author hewei
*/
public void setContext(Context context) {
this.context = context;
}
/**
* 获取挂载
* @param clazz
* @param <T>
* @return
*/
public <T> T getHook(Class<T> clazz) {
return (T) this;
}
/**
* 获取插件
* @param clazz
* @param <T>
* @return
*/
private <T> List<T> getPlugins(Class<T> clazz) {
List list = new ArrayList();
// 反射获取插件列表,不能用单例去弄,不然因为类释放的问题而导致测试用例出问题
try {
java.lang.reflect.Field field = this.context.getPlugins().getClass().getDeclaredField("plugins");
field.setAccessible(true);
List<Plugin> plugins = (List<Plugin>) field.get(this.context.getPlugins());
for (Plugin plugin : plugins) {
if (clazz.isInstance(plugin)) {
list.add(plugin);
}
}
} catch (Exception e) {
logger.error("获取插件列表失败!", e);
}
return list;
}
// ================================================= default ===============================================
@Override
public boolean clientUpsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
for (IUpsertPluginHook plugin : this.getPlugins(IUpsertPluginHook.class)) {
if (!plugin.clientUpsertSelectiveMethodGenerated(method, interfaze, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean clientUpsertByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable) {
for (IUpsertPluginHook plugin : this.getPlugins(IUpsertPluginHook.class)) {
if (!plugin.clientUpsertByExampleSelectiveMethodGenerated(method, interfaze, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean sqlMapUpsertSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {
for (IUpsertPluginHook plugin : this.getPlugins(IUpsertPluginHook.class)) {
if (!plugin.sqlMapUpsertSelectiveElementGenerated(element, columns, insertColumnsEle, insertValuesEle, setsEle, introspectedTable)) {
return false;
}
}
return true;
}
@Override
public boolean sqlMapUpsertByExampleSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable) {
for (IUpsertPluginHook plugin : this.getPlugins(IUpsertPluginHook.class)) {
if (!plugin.sqlMapUpsertByExampleSelectiveElementGenerated(element, columns, insertColumnsEle, insertValuesEle, setsEle, introspectedTable)) {
return false;
}
}
return true;
}
}
/*
* 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.hook;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.xml.XmlElement;
import java.util.List;
/**
* ---------------------------------------------------------------------------
*
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2018/4/27 11:09
* ---------------------------------------------------------------------------
*/
public interface IUpsertPluginHook {
/**
* upsertSelective 方法
* @param method
* @param interfaze
* @param introspectedTable
* @return
*/
boolean clientUpsertSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable);
/**
* upsertByExampleSelective 方法
* @param method
* @param interfaze
* @param introspectedTable
* @return
*/
boolean clientUpsertByExampleSelectiveMethodGenerated(Method method, Interface interfaze, IntrospectedTable introspectedTable);
/**
* upsertSelective xml
* @param element
* @param columns
* @param insertColumnsEle
* @param insertValuesEle
* @param setsEle
* @param introspectedTable
* @return
*/
boolean sqlMapUpsertSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable);
/**
* upsertByExampleSelective xml
* @param element
* @param columns
* @param insertColumnsEle
* @param insertValuesEle
* @param setsEle
* @param introspectedTable
* @return
*/
boolean sqlMapUpsertByExampleSelectiveElementGenerated(XmlElement element, List<IntrospectedColumn> columns, XmlElement insertColumnsEle, XmlElement insertValuesEle, XmlElement setsEle, IntrospectedTable introspectedTable);
}
...@@ -42,7 +42,7 @@ public class SelectiveEnhancedPluginTest { ...@@ -42,7 +42,7 @@ public class SelectiveEnhancedPluginTest {
*/ */
@BeforeClass @BeforeClass
public static void init() throws SQLException, IOException, ClassNotFoundException { public static void init() throws SQLException, IOException, ClassNotFoundException {
DBHelper.createDB("scripts/OldSelectiveEnhancedPlugin/init.sql"); DBHelper.createDB("scripts/SelectiveEnhancedPlugin/init.sql");
} }
/** /**
...@@ -54,11 +54,6 @@ public class SelectiveEnhancedPluginTest { ...@@ -54,11 +54,6 @@ public class SelectiveEnhancedPluginTest {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/mybatis-generator-without-ModelColumnPlugin.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/mybatis-generator-without-ModelColumnPlugin.xml");
tool.generate(); tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!"); Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin插件需配合com.itfsw.mybatis.generator.plugins.ModelColumnPlugin插件使用!");
// 2. 同时配置了OldSelectiveEnhancedPlugin插件
tool = MyBatisGeneratorTool.create("scripts/SelectiveEnhancedPlugin/mybatis-generator-with-OldSelectiveEnhancedPlugin.xml");
tool.generate();
Assert.assertEquals(tool.getWarnings().get(0), "itfsw:插件com.itfsw.mybatis.generator.plugins.SelectiveEnhancedPlugin不能和com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin插件同时使用!");
} }
/** /**
......
...@@ -19,7 +19,6 @@ package com.itfsw.mybatis.generator.plugins; ...@@ -19,7 +19,6 @@ package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.tools.*; import com.itfsw.mybatis.generator.plugins.tools.*;
import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSession;
import org.junit.Assert; import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.exception.XMLParserException;
...@@ -37,13 +36,6 @@ import java.sql.SQLException; ...@@ -37,13 +36,6 @@ import java.sql.SQLException;
* --------------------------------------------------------------------------- * ---------------------------------------------------------------------------
*/ */
public class UpsertPluginTest { public class UpsertPluginTest {
/**
* 初始化数据库
*/
@BeforeClass
public static void init() throws SQLException, IOException, ClassNotFoundException {
DBHelper.createDB("scripts/UpsertPlugin/init.sql");
}
/** /**
* 测试配置异常 * 测试配置异常
...@@ -67,7 +59,7 @@ public class UpsertPluginTest { ...@@ -67,7 +59,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsert() throws Exception { public void testUpsert() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
...@@ -99,7 +91,7 @@ public class UpsertPluginTest { ...@@ -99,7 +91,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertWithBLOBs() throws Exception { public void testUpsertWithBLOBs() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 多个 blob // 1. 多个 blob
...@@ -153,7 +145,7 @@ public class UpsertPluginTest { ...@@ -153,7 +145,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertSelective() throws Exception { public void testUpsertSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 普通 // 1. 普通
...@@ -192,7 +184,7 @@ public class UpsertPluginTest { ...@@ -192,7 +184,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertByExample() throws Exception { public void testUpsertByExample() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper"))); ObjectUtil tbMapper = new ObjectUtil(sqlSession.getMapper(loader.loadClass(packagz + ".TbMapper")));
...@@ -228,7 +220,7 @@ public class UpsertPluginTest { ...@@ -228,7 +220,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertByExampleWithBLOBs() throws Exception { public void testUpsertByExampleWithBLOBs() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 多个 blob // 1. 多个 blob
...@@ -289,7 +281,7 @@ public class UpsertPluginTest { ...@@ -289,7 +281,7 @@ public class UpsertPluginTest {
@Test @Test
public void testUpsertByExampleSelective() throws Exception { public void testUpsertByExampleSelective() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// 1. 普通 // 1. 普通
...@@ -334,7 +326,7 @@ public class UpsertPluginTest { ...@@ -334,7 +326,7 @@ public class UpsertPluginTest {
@Test @Test
public void testWithIdentityAndGeneratedAlwaysColumns() throws Exception { public void testWithIdentityAndGeneratedAlwaysColumns() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml"); MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/UpsertPlugin/mybatis-generator.xml");
tool.generate(new AbstractShellCallback() { tool.generate(() -> DBHelper.createDB("scripts/UpsertPlugin/init.sql"), new AbstractShellCallback() {
@Override @Override
public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception { public void reloadProject(SqlSession sqlSession, ClassLoader loader, String packagz) throws Exception {
// ------------------------------------------ upsert --------------------------------------------------- // ------------------------------------------ upsert ---------------------------------------------------
......
...@@ -64,33 +64,29 @@ public class DBHelper { ...@@ -64,33 +64,29 @@ public class DBHelper {
String password = properties.getProperty("password"); String password = properties.getProperty("password");
// 获取connection // 获取connection
Class.forName(driver); Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password); try (
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement(); Statement statement = connection.createStatement();
// 获取建表和初始化sql // 获取建表和初始化sql
InputStream inputStream = Resources.getResourceAsStream(resource); InputStream inputStream = Resources.getResourceAsStream(resource);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
// 读取sql语句执行 ) {
StringBuffer sb = new StringBuffer(); // 读取sql语句执行
String line; StringBuffer sb = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) { String line;
sb.append(line).append("\n"); while ((line = bufferedReader.readLine()) != null) {
if (line.matches(".*;$")) { sb.append(line).append("\n");
statement.execute(sb.toString()); if (line.matches(".*;$")) {
sb.setLength(0); statement.execute(sb.toString());
sb.setLength(0);
}
} }
} }
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
statement.close();
connection.close();
} }
/** /**
* 执行sql * 执行sql
*
* @param sqlSession * @param sqlSession
* @param sql * @param sql
* @return * @return
...@@ -102,7 +98,6 @@ public class DBHelper { ...@@ -102,7 +98,6 @@ public class DBHelper {
/** /**
* 执行sql * 执行sql
*
* @param connection * @param connection
* @param sql * @param sql
* @return * @return
......
/*
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',
`field_1` 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');
\ No newline at end of file
<?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.OldSelectiveEnhancedPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.UpsertPlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject=""/>
<!--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"/>
<columnOverride column="inc_f2" property="tsIncF2"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
<?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.OldSelectiveEnhancedPlugin" />
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject=""/>
<!--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"/>
<columnOverride column="inc_f2" property="tsIncF2"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
<?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.UpsertPlugin">
<property name="allowMultiQueries" value="true"/>
</plugin>
<plugin type="com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin"/>
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject=""/>
<!--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">
<columnOverride column="inc_f2" property="tsIncF2"/>
</table>
</context>
</generatorConfiguration>
\ 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.SelectiveEnhancedPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.OldSelectiveEnhancedPlugin" />
<plugin type="com.itfsw.mybatis.generator.plugins.ModelColumnPlugin"/>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${driver}" connectionURL="${url}" userId="${username}" password="${password}" />
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="" targetProject=""/>
<!--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"/>
<columnOverride column="inc_f2" property="tsIncF2"/>
</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