Commit 24b895d3 authored by fangzhipeng's avatar fangzhipeng

优化插件,增加批量插入方法,增加updateByEample分表

parent 13a110ac
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.2.13.fzp-SNAPSHOT</version>
<version>1.2.14.fzp-SNAPSHOT</version>
<packaging>jar</packaging>
<name>${project.groupId}:${project.artifactId}</name>
......@@ -175,32 +176,6 @@
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++build++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<build>
<plugins>
<!-- 发布中央仓库用 -->
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>nexus-staging-maven-plugin</artifactId>
<version>1.6.7</version>
<extensions>true</extensions>
<configuration>
<serverId>ossrh</serverId>
<nexusUrl>https://oss.sonatype.org/</nexusUrl>
<autoReleaseAfterClose>true</autoReleaseAfterClose>
</configuration>
</plugin>
<!-- release -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>2.5.3</version>
<configuration>
<autoVersionSubmodules>true</autoVersionSubmodules>
<useReleaseProfile>false</useReleaseProfile>
<releaseProfiles>release</releaseProfiles>
<goals>deploy</goals>
</configuration>
</plugin>
</plugins>
<!-- 配置java版本 不配置的话默认父类配置的是1.6-->
<pluginManagement>
<plugins>
......@@ -233,8 +208,8 @@
<connection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</connection>
<developerConnection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</developerConnection>
<url>https://github.com/itfsw/mybatis-generator-plugin</url>
<tag>V1.2.6</tag>
</scm>
<tag>V1.2.6</tag>
</scm>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++distribution++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
<!--
......@@ -245,13 +220,13 @@
http://www.trinea.cn/dev-tools/upload-java-jar-or-android-aar-to-maven-center-repository/
-->
<distributionManagement>
<snapshotRepository>
<id>ossrh</id>
<url>https://oss.sonatype.org/content/repositories/snapshots</url>
</snapshotRepository>
<repository>
<id>ossrh</id>
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2</url>
<id>maven-releases</id>
<url>http://nexus.yuceyi.com/repository/maven-releases/</url>
</repository>
<snapshotRepository>
<id>maven-snapshots</id>
<url>http://nexus.yuceyi.com/repository/maven-snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
/*
* 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.FormatTools;
import com.itfsw.mybatis.generator.plugins.utils.JavaElementGeneratorTools;
import com.itfsw.mybatis.generator.plugins.utils.XmlElementGeneratorTools;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* 批量插入插件
* ---------------------------------------------------------------------------
*
* @author: hewei
* @time:2017/1/13 9:33
* ---------------------------------------------------------------------------
*/
public class TableBatchInsertPlugin extends BasePlugin {
public static final String METHOD_BATCH_INSERT = "batchInsertSelective"; // 方法名
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是数据库为MySQL或者SQLserver,因为返回主键使用了JDBC的getGenereatedKeys方法获取主键
if ("com.mysql.jdbc.Driver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false
&& "com.microsoft.jdbc.sqlserver.SQLServer".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false
&& "com.microsoft.sqlserver.jdbc.SQLServerDriver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false
&& "com.mysql.cj.jdbc.Driver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false) {
warnings.add("itfsw:插件" + this.getClass().getTypeName() + "插件使用前提是数据库为MySQL或者SQLserver,因为返回主键使用了JDBC的getGenereatedKeys方法获取主键!");
return false;
}
return super.validate(warnings);
}
/**
* Java Client Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param interfaze
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
// 1. batchInsert
FullyQualifiedJavaType listType = FullyQualifiedJavaType.getNewListInstance();
listType.addTypeArgument(introspectedTable.getRules().calculateAllFieldsClass());
Method mBatchInsert;
if (split(introspectedTable)) {
interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Param"));
mBatchInsert = JavaElementGeneratorTools.generateMethod(
METHOD_BATCH_INSERT,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(listType, "list", "@Param(\"list\")"),
new Parameter(FullyQualifiedJavaType.getStringInstance(), "index", "@Param(\"index\")")
);
} else {
mBatchInsert = JavaElementGeneratorTools.generateMethod(
METHOD_BATCH_INSERT,
JavaVisibility.DEFAULT,
FullyQualifiedJavaType.getIntInstance(),
new Parameter(listType, "list")
);
}
commentGenerator.addGeneralMethodComment(mBatchInsert, introspectedTable);
// interface 增加方法
FormatTools.addMethodWithBestPosition(interfaze, mBatchInsert);
logger.debug("itfsw(批量插入插件):" + interfaze.getType().getShortName() + "增加batchInsertSelective方法。");
return true;
}
/**
* SQL Map Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param document
* @param introspectedTable
* @return
*/
@Override
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
// 1. batchInsert
XmlElement batchInsertEle = new XmlElement("insert");
batchInsertEle.addAttribute(new Attribute("id", METHOD_BATCH_INSERT));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
commentGenerator.addComment(batchInsertEle);
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
XmlElementGeneratorTools.useGeneratedKeys(batchInsertEle, introspectedTable);
String tableName = split(introspectedTable) ?
introspectedTable.getFullyQualifiedTableNameAtRuntime() + "#{index}" : introspectedTable.getFullyQualifiedTableNameAtRuntime();
batchInsertEle.addElement(new TextElement("insert into " + tableName));
StringBuilder sb = new StringBuilder("(");
for (IntrospectedColumn column : ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns())) {
sb.append(column.getActualColumnName()).append(",");
}
batchInsertEle.addElement(new TextElement(sb.substring(0, sb.length() - 1) + ")"));
// 添加foreach节点
XmlElement foreachElement = new XmlElement("foreach");
foreachElement.addAttribute(new Attribute("collection", "list"));
foreachElement.addAttribute(new Attribute("item", "item"));
foreachElement.addAttribute(new Attribute("separator", ","));
sb = new StringBuilder("(\n");
for (IntrospectedColumn column : ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns())) {
sb.append(getColumnStr(column)).append(",\n");
}
foreachElement.addElement(new TextElement(sb.substring(0, sb.length() - 2) + "\n )"));
// values 构建
batchInsertEle.addElement(new TextElement("values"));
batchInsertEle.addElement(foreachElement);
document.getRootElement().addElement(batchInsertEle);
logger.debug("itfsw(批量插入插件):" + introspectedTable.getMyBatis3XmlMapperFileName() + "增加batchInsert实现方法。");
return true;
}
private String getColumnStr(IntrospectedColumn column) {
String commonTemplate =
" #{item.javaProperty}";
String template =
" <if test=\"item.javaProperty != null\">\n" +
" #{item.javaProperty}\n" +
" </if>\n" +
" <if test=\"item.javaProperty == null\">\n" +
" defaultValue\n" +
" </if>";
if (column.getDefaultValue() == null) {
return commonTemplate.replaceAll("javaProperty", column.getJavaProperty()).replaceAll("columnName", column.getActualColumnName());
} else {
return template.replaceAll("javaProperty", column.getJavaProperty()).replaceAll("columnName", column.getActualColumnName()).replaceAll("defaultValue", column.getDefaultValue());
}
}
/**
* 判断是否要进行分表
*
* @param introspectedTable 表信息
* @return
*/
private boolean split(IntrospectedTable introspectedTable) {
String split = introspectedTable.getTableConfigurationProperty("split");
if ("true".equals(split)) {
return true;
}
return false;
}
}
\ No newline at end of file
......@@ -21,6 +21,7 @@ public class TableSplitPlugin extends BasePlugin {
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
logger.info("****************************测试断点");
if (!split(introspectedTable)) {
return true;
}
......@@ -107,6 +108,11 @@ public class TableSplitPlugin extends BasePlugin {
return joinIndex(element, introspectedTable);
}
@Override
public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
return joinIndex(element, introspectedTable);
}
@Override
public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
return joinIndex(element, introspectedTable);
......@@ -117,6 +123,11 @@ public class TableSplitPlugin extends BasePlugin {
return joinIndex(element, introspectedTable);
}
@Override
public boolean sqlMapSelectAllElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
return joinIndex(element, introspectedTable);
}
@Override
public boolean sqlMapUpdateByPrimaryKeySelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
return joinIndex(element, introspectedTable);
......@@ -127,6 +138,21 @@ public class TableSplitPlugin extends BasePlugin {
return joinIndex(element, introspectedTable);
}
@Override
public boolean sqlMapUpdateByPrimaryKeyWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
return joinIndex(element, introspectedTable);
}
@Override
public boolean sqlMapUpdateByExampleSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
return joinIndex(element, introspectedTable);
}
@Override
public boolean sqlMapUpdateByExampleWithoutBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
return joinIndex(element, introspectedTable);
}
@Override
public boolean sqlMapUpdateByExampleWithBLOBsElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
return joinIndex(element, introspectedTable);
......
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.tools.DBHelper;
import com.itfsw.mybatis.generator.plugins.tools.MyBatisGeneratorTool;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mybatis.generator.api.MyBatisGenerator;
/**
* @author fangzhipeng
* @date 2018/11/23
*/
public class TableBatchInsertPluginTest {
@BeforeClass
public static void init() throws Exception {
DBHelper.createDB("scripts/TableBatchInsertPlugin/init.sql");
}
@Test
public void testTableSplit() throws Exception {
MyBatisGeneratorTool tool = MyBatisGeneratorTool.create("scripts/TableBatchInsertPlugin/mybatis-generator-TableBatchInsertPlugin.xml");
MyBatisGenerator myBatisGenerator = tool.generate();
myBatisGenerator.getGeneratedXmlFiles();
}
}
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50617
Source Host : localhost:3306
Source Database : mybatis-generator-plugin
Target Server Type : MYSQL
Target Server Version : 50617
File Encoding : 65001
Date: 2017-06-26 17:30:13
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tb1
-- ----------------------------
DROP TABLE IF EXISTS `tb1`;
CREATE TABLE `tb1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`gmt_update` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`record_status` smallint(6) NOT NULL DEFAULT '0',
`market_type` int(11) NOT NULL COMMENT '选品类型 0-flash sale 1-best seller 2-new arrivial 3-price zone 4-cf mall',
`countryCode` varchar(10) NOT NULL COMMENT '国家二字码,小写',
`gender` int(5) NOT NULL COMMENT '性别 0-男 1-女 -1-未知',
`product_no` varchar(20) NOT NULL COMMENT '商品货号',
`product_id` int(11) NOT NULL COMMENT '商品Id spuId',
`price_local` double NOT NULL DEFAULT '0' COMMENT '活动价',
`sequence` int(11) NOT NULL DEFAULT '0' COMMENT '商品排序',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
\ 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.TableBatchInsertPlugin">
</plugin>
<!--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="tb1">
<property name="split" value="true"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
\ No newline at end of file
......@@ -20,15 +20,16 @@ SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
DROP TABLE IF EXISTS `tb1`;
CREATE TABLE `tb1` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`id` int(11) NOT NULL AUTO_INCREMENT,
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`gmt_update` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`record_status` smallint(6) NOT NULL DEFAULT '0',
`market_type` int(11) NOT NULL COMMENT '选品类型 0-flash sale 1-best seller 2-new arrivial 3-price zone 4-cf mall',
`countryCode` varchar(10) NOT NULL COMMENT '国家二字码,小写',
`gender` int(5) NOT NULL COMMENT '性别 0-男 1-女 -1-未知',
`product_no` varchar(20) NOT NULL COMMENT '商品货号',
`product_id` int(11) NOT NULL COMMENT '商品Id spuId',
`price_local` double NOT NULL DEFAULT '0' COMMENT '活动价',
`sequence` int(11) NOT NULL DEFAULT '0' COMMENT '商品排序',
PRIMARY KEY (`id`)
);
-- ----------------------------
-- Table structure for tb2
-- ----------------------------
DROP TABLE IF EXISTS `tb2`;
CREATE TABLE `tb2` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
);
\ No newline at end of file
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
\ No newline at end of file
......@@ -51,8 +51,5 @@
<property name="split" value="true"/>
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
<table tableName="tb2">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</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