Compare commits

...
33 Commits
Author SHA1 Message Date
hewei 7d910b7160 [maven-release-plugin] prepare release v1.0.3 2017-01-13 18:22:29 +08:00
hewei d8e61cef5a README.md增加新插件描述 2017-01-13 18:21:24 +08:00
hewei fc0d2adfd7 增加逻辑删除插件 2017-01-13 17:54:27 +08:00
hewei 2cfa1ddd2d 修正批量插入插件 2017-01-13 14:01:47 +08:00
hewei d12454d3aa 增加一些必要验证,同时增加批量插入插件 2017-01-13 13:21:19 +08:00
hewei d412fb37d3 一些修正和新增插件 2017-01-13 10:02:28 +08:00
hewei a316fceb49 版本更新 2017-01-12 18:48:57 +08:00
hewei a88e4ab07a [maven-release-plugin] prepare for next development iteration 2017-01-12 18:38:17 +08:00
hewei 88a4c10141 [maven-release-plugin] prepare release v1.0.2 2017-01-12 18:37:57 +08:00
hewei a616ccac67 版本更新 2017-01-12 18:37:31 +08:00
hewei 8d54c7559e [maven-release-plugin] prepare release v1.0.1 2017-01-12 18:34:34 +08:00
hewei 05558ab088 版本更新 2017-01-12 18:33:15 +08:00
hewei bf2045178f [maven-release-plugin] prepare release v1.0.1 2017-01-12 18:32:12 +08:00
hewei 9ec7290cdd 版本更新 2017-01-12 18:31:38 +08:00
hewei 58c65dc8b5 [maven-release-plugin] prepare release v1.0.1 2017-01-12 18:29:37 +08:00
hewei 5e5fe44a60 版本更新 2017-01-12 18:29:13 +08:00
hewei 195f1e631e [maven-release-plugin] prepare for next development iteration 2017-01-12 18:19:48 +08:00
hewei 5133c7b359 [maven-release-plugin] prepare release v1.0.1 2017-01-12 18:19:28 +08:00
hewei e4754d9c20 版本更新 2017-01-12 18:18:47 +08:00
hewei 3a55dd8c85 版本更新 2017-01-12 18:10:55 +08:00
hewei 6a6b991a3d [maven-release-plugin] prepare for next development iteration 2017-01-12 18:09:42 +08:00
hewei d8f0e0dd1d [maven-release-plugin] prepare release mybatis-generator-plugin-1.0.1 2017-01-12 18:09:11 +08:00
hewei 9ce992c728 增强Criteria的链式调用,添加andIf(boolean addIf, CriteriaAdd add)方法,实现链式调用中按条件增加查询语句 2017-01-12 18:07:20 +08:00
hewei ed19ffa96d Example 目标包修改插件 2017-01-12 14:19:35 +08:00
hewei b564e9d98b 修改日志级别描述 2017-01-12 13:42:48 +08:00
hewei cbc9c5a7c6 修改README.md 描述 2017-01-12 10:08:02 +08:00
hewei 315a896003 修复README.md GitHub显示异常 2017-01-11 19:05:10 +08:00
hewei ab4c5e0f6f 修复README.md GitHub显示异常 2017-01-11 19:02:39 +08:00
hewei 74ab3a66f9 修复README.md GitHub显示异常 2017-01-11 19:00:47 +08:00
hewei a864c9784a 修复README.md GitHub显示异常 2017-01-11 18:56:52 +08:00
hewei 0eb971fa53 增加README.md Maven引用地址介绍 2017-01-11 18:47:20 +08:00
hewei 6e132d7dc2 增加README.md介绍 2017-01-11 18:44:09 +08:00
hewei 7393b26105 [maven-release-plugin] prepare for next development iteration 2017-01-11 13:38:36 +08:00
13 changed files with 1313 additions and 26 deletions
+296 -1
View File
@@ -1 +1,296 @@
# mybatis-generator-plugin
# 这是 MyBatis Generator 插件的拓展插件包
应该说使用Mybatis就一定离不开[MyBatis Generator](https://github.com/mybatis/generator)这款代码生成插件,而这款插件自身还提供了插件拓展功能用于强化插件本身,官方已经提供了一些[拓展插件](http://www.mybatis.org/generator/reference/plugins.html),本项目的目的也是通过该插件机制来强化Mybatis Generator本身,方便和减少我们平时的代码开发量。
>因为插件是本人兴之所至所临时发布的项目(本人已近三年未做JAVA开发,代码水平请大家见谅),但基本插件都是在实际项目中经过检验的请大家放心使用,但因为项目目前主要数据库为MySQL,Mybatis实现使用Mapper.xml方式,所以代码生成时对于其他数据库和注解方式的支持未予考虑,请大家见谅。
---------------------------------------
插件列表:
* 查询单条数据插件(SelectOneByExamplePlugin)
* MySQL分页插件(LimitPlugin)
* 数据Model链式构建插件(ModelBuilderPlugin)
* Example Criteria 增强插件(CriteriaBuilderPlugin)
* Example 目标包修改插件(ExampleTargetPlugin)
* 批量插入插件(BatchInsertPlugin)
* 逻辑删除插件(LogicalDeletePlugin)
---------------------------------------
Maven引用:
```xml
<dependency>
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.0.3</version>
</dependency>
```
---------------------------------------
### 1. 查询单条数据插件
对应表Mapper接口增加了方法
插件:
```xml
<!-- 查询单条数据插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.SelectOneByExamplePlugin"/>
```
使用:
```java
public interface TbMapper {
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method corresponds to the database table tb
*
* @mbg.generated
* @author hewei
*/
Tb selectOneByExample(TbExample example);
}
```
### 2. MySQL分页插件
对应表Example类增加了方法
插件:
```xml
<!-- MySQL分页插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.LimitPlugin"/>
```
使用:
```java
public class TbExample {
/**
* 这是Mybatis Generator拓展插件生成的属性(请勿删除).
* This field corresponds to the database table tb
*
* @mbg.generated
* @author hewei
*/
protected Integer offset;
/**
* 这是Mybatis Generator拓展插件生成的属性(请勿删除).
* This field corresponds to the database table tb
*
* @mbg.generated
* @author hewei
*/
protected Integer rows;
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method corresponds to the database table rc_user_token
*
* @mbg.generated
* @author hewei
*/
public void limit(Integer rows) {
this.rows = rows;
}
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method corresponds to the database table rc_user_token
*
* @mbg.generated
* @author hewei
*/
public void limit(Integer offset, Integer rows) {
this.offset = offset;
this.rows = rows;
}
/**
* 这是Mybatis Generator拓展插件生成的方法(请勿删除).
* This method corresponds to the database table tb
*
* @mbg.generated
* @author hewei
*/
public void page(Integer page, Integer pageSize) {
this.offset = page * pageSize;
this.rows = pageSize;
}
// offset 和 rows 的getter&setter
// 修正了clear方法
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table tb
*
* @mbg.generated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
rows = null;
offset = null;
}
}
```
### 3. 数据Model链式构建插件
这个是仿jquery的链式调用强化了表的Model的赋值操作
插件:
```xml
<!-- 数据Model链式构建插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ModelBuilderPlugin"/>
```
使用:
```java
public class Test {
public static void main(String[] args) {
// 直接new表Model的内部Builder类,赋值后调用build()方法返回对象
Tb table = new Tb.Builder()
.field1("xx")
.field2("xx")
.field3("xx")
.field4("xx")
.build();
}
}
```
### 4. Example Criteria 增强插件(example,andIf)
* 表Example增加Criteria的快速返回example()方法。
* Criteria链式调用增强,以前如果有按条件增加的查询语句会打乱链式查询构建,现在有了andIf(boolean ifAdd, CriteriaAdd add)方法可一直使用链式调用下去。
插件:
```xml
<!-- Example Criteria 增强插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.CriteriaBuilderPlugin"/>
```
使用:
```java
public class Test {
public static void main(String[] args) {
// -----------------------------------example-----------------------------------
// 表Example.Criteria增加了工厂方法example()支持,使用后可链式构建查询条件使用example()返回Example对象
TbExample ex = new TbExample()
.createCriteria()
.andField1EqualTo(1)
.andField2EqualTo("xxx")
.example();
this.tbMapper.selectByExample(ex);
// -----------------------------------andIf-----------------------------------
// Criteria增强了链式调用,现在一些按条件增加的查询条件不会打乱链式调用了
// old
TbExample oldEx = new TbExample();
TbExample.Criteria criteria = oldEx
.createCriteria()
.andField1EqualTo(1)
.andField2EqualTo("xxx");
// 如果随机数大于0.5,附加Field3查询条件
if (Math.random() > 0.5){
criteria.andField3EqualTo(2)
.andField4EqualTo(new Date());
}
this.tbMapper.selectByExample(oldEx);
// new
TbExample newEx;
newEx = new TbExample()
.createCriteria()
.andField1EqualTo(1)
.andField2EqualTo("xxx")
// 如果随机数大于0.5,附加Field3查询条件
.andIf(Math.random() > 0.5, new TbExample.Criteria.CriteriaAdd() {
@Override
public TbExample.Criteria add(TbExample.Criteria add) {
return add.andField3EqualTo(2)
.andField4EqualTo(new Date());
}
})
// 当然最简洁的写法是采用java8的Lambda表达式,当然你的项目是Java8+
.andIf(Math.random() > 0.5, add -> add
.andField3EqualTo(2)
.andField4EqualTo(new Date())
)
.example();
this.tbMapper.selectByExample(newEx);
}
}
```
### 5. Example 目标包修改插件
Mybatis Generator 插件默认把Model类和Example类都生成到一个包下,这样该包下类就会很多不方便区分,该插件目的就是把Example类独立到一个新包下,方便查看。
插件:
```xml
<!-- Example 目标包修改插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.ExampleTargetPlugin">
<!-- 修改Example类生成到目标包下 -->
<property name="targetPackage" value="com.itfsw.mybatis.generator.dao.example"/>
</plugin>
```
### 6. 批量插入插件
提供了一个批量插入batchInsert方法,因为方法使用了使用了JDBC的getGenereatedKeys方法返回插入主键,所以只能在MYSQL和SQLServer下使用。
插件:
```xml
<!-- 批量插入插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.BatchInsertPlugin"/>
```
使用:
```java
public class Test {
public static void main(String[] args) {
// 构建插入数据
List<Tb> list = new ArrayList<>();
list.add(new Tb.Builder()
.field1(0)
.field2("xx0")
.field3(0)
.field4(new Date())
.build()
);
list.add(new Tb.Builder()
.field1(1)
.field2("xx1")
.field3(1)
.field4(new Date())
.build()
);
int inserted = this.tbMapper.batchInsert(list);
}
}
```
### 7. 逻辑删除插件
因为很多实际项目数据都不允许物理删除,多采用逻辑删除,所以单独为逻辑删除做了一个插件,方便使用。
插件:
```xml
<xml>
<!-- 逻辑删除插件 -->
<plugin type="com.itfsw.mybatis.generator.plugins.LogicalDeletePlugin">
<!-- 这里配置的是全局逻辑删除列和逻辑删除值,当然在table中配置的值会覆盖该全局配置 -->
<!-- 逻辑删除列类型只能为数字、字符串或者布尔类型 -->
<property name="logicalDeleteColumn" value="del_flag"/>
<!-- 未设置该属性或者该属性的值为null或者NULL,逻辑删除时会把该字段置为NULL。 -->
<property name="logicalDeleteValue" value="9"/>
</plugin>
<table tableName="tb">
<!-- 这里可以单独表配置逻辑删除列和删除值,覆盖全局配置 -->
<property name="logicalDeleteColumn" value="del_flag"/>
<property name="logicalDeleteValue" value="1"/>
</table>
</xml>
```
使用:
```java
public class Test {
public static void main(String[] args) {
// 1. 逻辑删除ByExample
TbExample ex = new TbExample()
.createCriteria()
.andField1EqualTo(1)
.example();
this.tbMapper.logicalDeleteByExample(ex);
// 2. 逻辑删除ByPrimaryKey
this.tbMapper.logicalDeleteByPrimaryKey(1L);
// 3. 同时Example中提供了一个快捷方法来过滤逻辑删除数据
TbExample selEx = new TbExample()
.createCriteria()
.andField1EqualTo(1)
// 新增了一个andDeleted方法过滤逻辑删除数据
.andDeleted(true)
// 当然也可直接使用逻辑删除列的查询方法,我们数据Model中定义了一个逻辑删除常量DEL_FLAG
.andDelFlagEqualTo(Tb.DEL_FLAG)
.example();
List<Tb> list = this.tbMapper.selectByExample(selEx);
}
}
```
+3 -2
View File
@@ -3,7 +3,7 @@
<groupId>com.itfsw</groupId>
<artifactId>mybatis-generator-plugin</artifactId>
<version>1.0.0</version>
<version>1.0.3</version>
<packaging>jar</packaging>
<name>${project.groupId}:${project.artifactId}</name>
@@ -175,7 +175,7 @@
<connection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</connection>
<developerConnection>scm:git:https://github.com/itfsw/mybatis-generator-plugin.git</developerConnection>
<url>https://github.com/itfsw/mybatis-generator-plugin</url>
<tag>v1.0.0</tag>
<tag>v1.0.3</tag>
</scm>
<!-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++distribution++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -->
@@ -184,6 +184,7 @@
http://central.sonatype.org/pages/working-with-pgp-signatures.html
http://www.cnblogs.com/gaoxing/p/4359795.html
http://blog.csdn.net/ssrc0604hx/article/details/51513414
http://www.trinea.cn/dev-tools/upload-java-jar-or-android-aar-to-maven-center-repository/
-->
<distributionManagement>
<snapshotRepository>
@@ -0,0 +1,195 @@
/*
* 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.CommentTools;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
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 org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.config.GeneratedKey;
import org.mybatis.generator.internal.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* ---------------------------------------------------------------------------
* 批量插入插件
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/1/13 9:33
* ---------------------------------------------------------------------------
*/
public class BatchInsertPlugin extends PluginAdapter {
private static final Logger logger = LoggerFactory.getLogger(BatchInsertPlugin.class);
public static final String METHOD_BATCH_INSERT = "batchInsert"; // 方法名
public static final String METHOD_BATCH_INSERT_SELECTIVE = "batchInsertSelective"; // 方法名
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是targetRuntime为MyBatis3
if (StringUtility.stringHasValue(getContext().getTargetRuntime()) && "MyBatis3".equalsIgnoreCase(getContext().getTargetRuntime()) == false) {
logger.warn("itfsw:插件" + this.getClass().getTypeName() + "要求运行targetRuntime必须为MyBatis3!");
return false;
}
// 插件使用前提是数据库为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){
logger.warn("itfsw:插件" + this.getClass().getTypeName() + "插件使用前提是数据库为MySQL或者SQLserver,因为返回主键使用了JDBC的getGenereatedKeys方法获取主键!");
return false;
}
return true;
}
/**
* 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) {
logger.debug("itfsw:生成" + interfaze.getType() + "对应batchInsert方法...");
// 方法生成
Method method = new Method(METHOD_BATCH_INSERT);
// 方法可见性 interface会忽略
// method.setVisibility(JavaVisibility.PUBLIC);
// 返回值类型
method.setReturnType(FullyQualifiedJavaType.getIntInstance());
// 添加参数
FullyQualifiedJavaType type = FullyQualifiedJavaType.getNewListInstance();
type.addTypeArgument(introspectedTable.getRules().calculateAllFieldsClass());
method.addParameter(new Parameter(type, "list", "@Param(\"list\")"));
// 添加方法说明
CommentTools.addGeneralMethodComment(method, introspectedTable);
// interface 增加方法
interfaze.addMethod(method);
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) {
// batchInsert
this.generatorBatchInsertXml(document, introspectedTable);
return true;
}
/**
* 生成BatchInsert对应的xml
* @param document
* @param introspectedTable
*/
private void generatorBatchInsertXml(Document document, IntrospectedTable introspectedTable) {
XmlElement element = new XmlElement("insert"); //$NON-NLS-1$
element.addAttribute(new Attribute("id", METHOD_BATCH_INSERT)); //$NON-NLS-1$
// 参数类型
element.addAttribute(new Attribute("parameterType", FullyQualifiedJavaType.getNewListInstance().getFullyQualifiedName()));
// 添加注释(!!!必须添加注释,overwrite覆盖生成时,@see XmlFileMergerJaxp.isGeneratedNode会去判断注释中是否存在OLD_ELEMENT_TAGS中的一点,例子:@mbg.generated)
CommentTools.addComment(element);
GeneratedKey gk = introspectedTable.getGeneratedKey();
if (gk != null) {
IntrospectedColumn introspectedColumn = introspectedTable.getColumn(gk.getColumn());
// if the column is null, then it's a configuration error. The
// warning has already been reported
if (introspectedColumn != null) {
// 使用JDBC的getGenereatedKeys方法获取主键并赋值到keyProperty设置的领域模型属性中。所以只支持MYSQL和SQLServer
element.addAttribute(new Attribute("useGeneratedKeys", "true")); //$NON-NLS-1$ //$NON-NLS-2$
element.addAttribute(new Attribute("keyProperty", introspectedColumn.getJavaProperty())); //$NON-NLS-1$
element.addAttribute(new Attribute("keyColumn", introspectedColumn.getActualColumnName())); //$NON-NLS-1$
}
}
StringBuilder insertClause = new StringBuilder();
StringBuilder valuesClause = new StringBuilder();
insertClause.append("insert into "); //$NON-NLS-1$
insertClause.append(introspectedTable.getFullyQualifiedTableNameAtRuntime());
insertClause.append(" ("); //$NON-NLS-1$
valuesClause.append(" ("); //$NON-NLS-1$
List<String> valuesClauses = new ArrayList<String>();
List<IntrospectedColumn> columns = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
for (int i = 0; i < columns.size(); i++) {
IntrospectedColumn introspectedColumn = columns.get(i);
insertClause.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
// 生成foreach下插入values
valuesClause.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, "item."));
if (i + 1 < columns.size()) {
insertClause.append(", "); //$NON-NLS-1$
valuesClause.append(", "); //$NON-NLS-1$
}
}
insertClause.append(')');
element.addElement(new TextElement(insertClause.toString()));
valuesClause.append(')');
valuesClauses.add(valuesClause.toString());
// 添加foreach节点
XmlElement foreachElement = new XmlElement("foreach");
foreachElement.addAttribute(new Attribute("collection", "list"));
foreachElement.addAttribute(new Attribute("item", "item"));
foreachElement.addAttribute(new Attribute("separator", ","));
for (String clause : valuesClauses) {
foreachElement.addElement(new TextElement(clause));
}
// values 构建
element.addElement(new TextElement("values"));
element.addElement(foreachElement);
if (context.getPlugins().sqlMapInsertElementGenerated(element, introspectedTable)) {
document.getRootElement().addElement(element);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2014.
* 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.
@@ -17,9 +17,12 @@
package com.itfsw.mybatis.generator.plugins;
import com.itfsw.mybatis.generator.plugins.utils.CommentTools;
import com.itfsw.mybatis.generator.plugins.utils.InnerInterface;
import com.itfsw.mybatis.generator.plugins.utils.InnerInterfaceWrapperToInnerClass;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.internal.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -38,7 +41,13 @@ public class CriteriaBuilderPlugin extends PluginAdapter {
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是targetRuntime为MyBatis3
if (StringUtility.stringHasValue(getContext().getTargetRuntime()) && "MyBatis3".equalsIgnoreCase(getContext().getTargetRuntime()) == false ){
logger.warn("itfsw:插件"+this.getClass().getTypeName()+"要求运行targetRuntime必须为MyBatis3!");
return false;
}
return true;
}
@@ -55,7 +64,10 @@ public class CriteriaBuilderPlugin extends PluginAdapter {
List<InnerClass> innerClasses = topLevelClass.getInnerClasses();
for (InnerClass innerClass : innerClasses) {
if ("Criteria".equals(innerClass.getType().getShortName())) {
// 工厂方法
addFactoryMethodToCriteria(topLevelClass, innerClass, introspectedTable);
// andIf
addAndIfMethodToCriteria(topLevelClass, innerClass, introspectedTable);
}
}
@@ -64,7 +76,7 @@ public class CriteriaBuilderPlugin extends PluginAdapter {
if (!"createCriteriaInternal".equals(method.getName()))
continue;
method.getBodyLines().set(0, "Criteria criteria = new Criteria(this);");
logger.info("itfsw:CriteriaBuilder修改Example的createCriteriaInternal方法,修改构造Criteria时传入Example对象");
logger.debug("itfsw:CriteriaBuilder修改Example的createCriteriaInternal方法,修改构造Criteria时传入Example对象");
}
return true;
}
@@ -87,7 +99,7 @@ public class CriteriaBuilderPlugin extends PluginAdapter {
if (method.isConstructor()) {
method.addParameter(new Parameter(topLevelClass.getType(), "example"));
method.addBodyLine("this.example = example;");
logger.info("itfsw:CriteriaBuilder修改Criteria的构造方法,增加example参数");
logger.debug("itfsw:CriteriaBuilder修改Criteria的构造方法,增加example参数");
}
}
@@ -98,6 +110,47 @@ public class CriteriaBuilderPlugin extends PluginAdapter {
method.addBodyLine("return this.example;");
CommentTools.addGeneralMethodComment(method, introspectedTable);
innerClass.addMethod(method);
logger.info("itfsw:CriteriaBuilder增加工厂方法example");
logger.debug("itfsw:CriteriaBuilder增加工厂方法example");
}
/**
* 增强Criteria的链式调用,添加andIf(boolean addIf, CriteriaAdd add)方法,实现链式调用中按条件增加查询语句
*
* @param topLevelClass
* @param innerClass
* @param introspectedTable
*/
private void addAndIfMethodToCriteria(TopLevelClass topLevelClass, InnerClass innerClass, IntrospectedTable introspectedTable){
// 添加接口CriteriaAdd
InnerInterface criteriaAddInterface = new InnerInterface("ICriteriaAdd");
criteriaAddInterface.setVisibility(JavaVisibility.PUBLIC);
CommentTools.addInterfaceComment(criteriaAddInterface, introspectedTable);
// ICriteriaAdd增加接口add
Method addMethod = new Method("add");
addMethod.setReturnType(innerClass.getType());
addMethod.addParameter(new Parameter(innerClass.getType(), "add"));
CommentTools.addGeneralMethodComment(addMethod, introspectedTable);
criteriaAddInterface.addMethod(addMethod);
logger.debug("itfsw:Criteria.ICriteriaAdd增加接口add");
InnerClass innerClassWrapper = new InnerInterfaceWrapperToInnerClass(criteriaAddInterface);
innerClass.addInnerClass(innerClassWrapper);
// 添加andIf方法
Method method = new Method("andIf");
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(innerClass.getType());
method.addParameter(new Parameter(FullyQualifiedJavaType.getBooleanPrimitiveInstance(), "ifAdd"));
method.addParameter(new Parameter(criteriaAddInterface.getType(), "add"));
method.addBodyLine("if (ifAdd) {");
method.addBodyLine("add.add(this);");
method.addBodyLine("}");
method.addBodyLine("return this;");
CommentTools.addGeneralMethodComment(method, introspectedTable);
innerClass.addMethod(method);
logger.debug("itfsw:Criteria增加方法andIf");
}
}
@@ -0,0 +1,86 @@
/*
*
* * 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 org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.JavaModelGeneratorConfiguration;
import org.mybatis.generator.internal.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Properties;
/**
* ---------------------------------------------------------------------------
* Example类生成位置修改
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/1/12 12:36
* ---------------------------------------------------------------------------
*/
public class ExampleTargetPlugin extends PluginAdapter {
public static final String TARGET_PACKAGE_KEY = "targetPackage"; // 配置targetPackage名
private static final Logger logger = LoggerFactory.getLogger(ExampleTargetPlugin.class);
private static String targetPackage; // 目标包
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是targetRuntime为MyBatis3
if (StringUtility.stringHasValue(getContext().getTargetRuntime()) && "MyBatis3".equalsIgnoreCase(getContext().getTargetRuntime()) == false ){
logger.warn("itfsw:插件"+this.getClass().getTypeName()+"要求运行targetRuntime必须为MyBatis3!");
return false;
}
// 获取配置的目标package
Properties properties = getProperties();
this.targetPackage = properties.getProperty(TARGET_PACKAGE_KEY);
if (this.targetPackage == null){
logger.warn("请配置com.itfsw.mybatis.generator.plugins.ExampleTargetPlugin插件的目标包名(targetPackage)!");
return false;
}
return true;
}
/**
* 初始化阶段
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param introspectedTable
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
String exampleType = introspectedTable.getExampleType();
// 修改包名
Context context = getContext();
JavaModelGeneratorConfiguration configuration = context.getJavaModelGeneratorConfiguration();
String targetPackage = configuration.getTargetPackage();
String newExampleType = exampleType.replace(targetPackage, this.targetPackage);
introspectedTable.setExampleType(newExampleType);
logger.debug("itfsw:修改"+exampleType+"的包到"+this.targetPackage);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2014.
* 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.
@@ -23,6 +23,7 @@ import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.internal.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -41,9 +42,21 @@ public class LimitPlugin extends PluginAdapter {
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是targetRuntime为MyBatis3
if (StringUtility.stringHasValue(getContext().getTargetRuntime()) && "MyBatis3".equalsIgnoreCase(getContext().getTargetRuntime()) == false ){
logger.warn("itfsw:插件"+this.getClass().getTypeName()+"要求运行targetRuntime必须为MyBatis3!");
return false;
}
// 该插件只支持MYSQL
if ("com.mysql.jdbc.Driver".equalsIgnoreCase(this.getContext().getJdbcConnectionConfiguration().getDriverClass()) == false){
logger.warn("itfsw:插件"+this.getClass().getTypeName()+"只支持MySQL数据库!");
return false;
}
return true;
}
/**
* ModelExample Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
@@ -69,7 +82,7 @@ public class LimitPlugin extends PluginAdapter {
rows.setType(integerWrapper);
CommentTools.addFieldComment(rows, introspectedTable);
topLevelClass.addField(rows);
logger.info("itfsw:分页插件增加Example的offset和rows字段");
logger.debug("itfsw:分页插件增加Example的offset和rows字段");
// 增加getter && setter 方法
Method setOffset = new Method();
@@ -103,7 +116,7 @@ public class LimitPlugin extends PluginAdapter {
getRows.addBodyLine("return rows;");
CommentTools.addGeneralMethodComment(getRows, introspectedTable);
topLevelClass.addMethod(getRows);
logger.info("itfsw:分页插件增加Example的offset和rows的getter和setter");
logger.debug("itfsw:分页插件增加Example的offset和rows的getter和setter");
// 提供几个快捷方法
Method setLimit = new Method();
@@ -123,7 +136,7 @@ public class LimitPlugin extends PluginAdapter {
setLimit2.addBodyLine("this.rows = rows;");
CommentTools.addGeneralMethodComment(setLimit2, introspectedTable);
topLevelClass.addMethod(setLimit2);
logger.info("itfsw:分页插件增加Example的limit方法");
logger.debug("itfsw:分页插件增加Example的limit方法");
Method setPage = new Method();
setPage.setVisibility(JavaVisibility.PUBLIC);
@@ -134,7 +147,7 @@ public class LimitPlugin extends PluginAdapter {
setPage.addBodyLine("this.rows = pageSize;");
CommentTools.addGeneralMethodComment(setPage, introspectedTable);
topLevelClass.addMethod(setPage);
logger.info("itfsw:分页插件增加Example的page方法");
logger.debug("itfsw:分页插件增加Example的page方法");
// !!! clear 方法增加 offset 和 rows的清理
List<Method> methodList = topLevelClass.getMethods();
@@ -142,7 +155,7 @@ public class LimitPlugin extends PluginAdapter {
if (method.getName().equals("clear")){
method.addBodyLine("rows = null;");
method.addBodyLine("offset = null;");
logger.info("itfsw:分页插件修正Example的clear方法,增加rows和offset字段的清空");
logger.debug("itfsw:分页插件修正Example的clear方法,增加rows和offset字段的清空");
}
}
@@ -0,0 +1,409 @@
/*
* 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.CommentTools;
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.PluginAdapter;
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.MyBatis3FormattingUtilities;
import org.mybatis.generator.internal.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.JDBCType;
import java.util.*;
/**
* ---------------------------------------------------------------------------
* 逻辑删除插件
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/1/13 14:08
* ---------------------------------------------------------------------------
*/
public class LogicalDeletePlugin extends PluginAdapter {
private static final Logger logger = LoggerFactory.getLogger(LogicalDeletePlugin.class);
public static final String METHOD_LOGICAL_DELETE_BY_EXAMPLE = "logicalDeleteByExample"; // 方法名
public static final String METHOD_LOGICAL_DELETE_BY_PRIMARY_KEY = "logicalDeleteByPrimaryKey"; // 方法名
public static final String LOGICAL_DELETE_COLUMN_KEY = "logicalDeleteColumn"; // 逻辑删除列-Key
public static final String LOGICAL_DELETE_VALUE_KEY = "logicalDeleteValue"; // 逻辑删除值-Key
public static final String DEL_FLAG_NAME = "DEL_FLAG"; // 逻辑删除标志位常量名称
public static final String METHOD_LOGICAL_DELETE = "andDeleted"; // 逻辑删除查询方法
private IntrospectedColumn logicalDeleteColumn; // 逻辑删除列
private String logicalDeleteValue; // 逻辑删除值
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是targetRuntime为MyBatis3
if (StringUtility.stringHasValue(getContext().getTargetRuntime()) && "MyBatis3".equalsIgnoreCase(getContext().getTargetRuntime()) == false ){
logger.warn("itfsw:插件"+this.getClass().getTypeName()+"要求运行targetRuntime必须为MyBatis3!");
return false;
}
return true;
}
/**
* 初始化阶段
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param introspectedTable
* @return
*/
@Override
public void initialized(IntrospectedTable introspectedTable) {
// 1. 首先获取全局配置
Properties properties = getProperties();
String logicalDeleteColumn = properties.getProperty(LOGICAL_DELETE_COLUMN_KEY);
this.logicalDeleteValue = properties.getProperty(LOGICAL_DELETE_VALUE_KEY);
// 2. 获取表单独配置,如果有则覆盖全局配置
if (introspectedTable.getTableConfigurationProperty(LOGICAL_DELETE_COLUMN_KEY) != null){
logicalDeleteColumn = introspectedTable.getTableConfigurationProperty(LOGICAL_DELETE_COLUMN_KEY);
}
if (introspectedTable.getTableConfigurationProperty(LOGICAL_DELETE_VALUE_KEY) != null){
this.logicalDeleteValue = introspectedTable.getTableConfigurationProperty(LOGICAL_DELETE_VALUE_KEY);
}
// 3. 判断该表是否存在逻辑删除列
this.logicalDeleteColumn = null;
List<IntrospectedColumn> columns = introspectedTable.getAllColumns();
for (IntrospectedColumn column : columns) {
if (column.getActualColumnName().equalsIgnoreCase(logicalDeleteColumn)){
// 判断字段类型
JDBCType type = JDBCType.valueOf(column.getJdbcType());
if (JDBCType.BIGINT == type
|| JDBCType.BIT == type
|| JDBCType.BOOLEAN == type
|| JDBCType.CHAR == type
|| JDBCType.DECIMAL == type
|| JDBCType.DOUBLE == type
|| JDBCType.FLOAT == type
|| JDBCType.INTEGER == type
|| JDBCType.LONGNVARCHAR == type
|| JDBCType.LONGVARCHAR == type
|| JDBCType.NCHAR == type
|| JDBCType.NUMERIC == type
|| JDBCType.NVARCHAR == type
|| JDBCType.SMALLINT == type
|| JDBCType.TINYINT == type
|| JDBCType.VARCHAR == type){
this.logicalDeleteColumn = column;
} else {
logger.warn("itfsw:插件"+this.getClass().getTypeName()+"逻辑删除列的类型不支持(请使用数字列,字符串列,布尔列)!");
}
}
}
}
/**
* 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) {
if (this.logicalDeleteColumn != null){
// 1. 逻辑删除ByExample
Method mLogicalDeleteByExample = new Method(METHOD_LOGICAL_DELETE_BY_EXAMPLE);
// 返回值类型
mLogicalDeleteByExample.setReturnType(FullyQualifiedJavaType.getIntInstance());
// 添加参数
FullyQualifiedJavaType type = new FullyQualifiedJavaType(introspectedTable.getExampleType());
mLogicalDeleteByExample.addParameter(new Parameter(type, "example"));
// 添加方法说明
CommentTools.addGeneralMethodComment(mLogicalDeleteByExample, introspectedTable);
// interface 增加方法
interfaze.addMethod(mLogicalDeleteByExample);
// 2. 判断是否有主键,生成主键删除方法
if (introspectedTable.hasPrimaryKeyColumns()){
// 1. 逻辑删除ByExample
Method mLogicalDeleteByPrimaryKey = new Method(METHOD_LOGICAL_DELETE_BY_PRIMARY_KEY);
// 返回值类型
mLogicalDeleteByPrimaryKey.setReturnType(FullyQualifiedJavaType.getIntInstance());
// 添加参数
Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
if (introspectedTable.getRules().generatePrimaryKeyClass()) {
FullyQualifiedJavaType type1 = new FullyQualifiedJavaType(introspectedTable.getPrimaryKeyType());
importedTypes.add(type1);
mLogicalDeleteByPrimaryKey.addParameter(new Parameter(type1, "key")); //$NON-NLS-1$
} else {
// no primary key class - fields are in the base class
// if more than one PK field, then we need to annotate the
// parameters
// for MyBatis
List<IntrospectedColumn> introspectedColumns = introspectedTable.getPrimaryKeyColumns();
boolean annotate = introspectedColumns.size() > 1;
if (annotate) {
importedTypes.add(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Param")); //$NON-NLS-1$
}
StringBuilder sb = new StringBuilder();
for (IntrospectedColumn introspectedColumn : introspectedColumns) {
FullyQualifiedJavaType type1 = introspectedColumn.getFullyQualifiedJavaType();
importedTypes.add(type1);
Parameter parameter = new Parameter(type1, introspectedColumn.getJavaProperty());
if (annotate) {
sb.setLength(0);
sb.append("@Param(\""); //$NON-NLS-1$
sb.append(introspectedColumn.getJavaProperty());
sb.append("\")"); //$NON-NLS-1$
parameter.addAnnotation(sb.toString());
}
mLogicalDeleteByPrimaryKey.addParameter(parameter);
}
}
// 添加方法说明
CommentTools.addGeneralMethodComment(mLogicalDeleteByPrimaryKey, introspectedTable);
// interface 增加方法
interfaze.addImportedTypes(importedTypes);
interfaze.addMethod(mLogicalDeleteByPrimaryKey);
}
}
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) {
if (this.logicalDeleteColumn != null){
// 1. 逻辑删除ByExample
XmlElement logicalDeleteByExample = new XmlElement("update"); //$NON-NLS-1$
logicalDeleteByExample.addAttribute(new Attribute("id", METHOD_LOGICAL_DELETE_BY_EXAMPLE));
logicalDeleteByExample.addAttribute(new Attribute("parameterType", "map")); //$NON-NLS-1$ //$NON-NLS-2$
CommentTools.addComment(logicalDeleteByExample);
StringBuilder sb = new StringBuilder();
sb.append("update "); //$NON-NLS-1$
sb.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
sb.append(" set ");
// 更新逻辑删除字段
sb.append(this.logicalDeleteColumn.getActualColumnName());
sb.append(" = ");
// 判断字段类型
JDBCType type = JDBCType.valueOf(this.logicalDeleteColumn.getJdbcType());
if (this.logicalDeleteValue == null || "NULL".equalsIgnoreCase(this.logicalDeleteValue)){
sb.append("NULL");
} else if (JDBCType.CHAR == type
|| JDBCType.LONGNVARCHAR == type
|| JDBCType.LONGVARCHAR == type
|| JDBCType.NCHAR == type
|| JDBCType.NVARCHAR == type
|| JDBCType.VARCHAR == type){
sb.append("'");
sb.append(this.logicalDeleteValue);
sb.append("'");
} else {
sb.append(this.logicalDeleteValue);
}
logicalDeleteByExample.addElement(new TextElement(sb.toString()));
logicalDeleteByExample.addElement(XmlElementGeneratorTools.getUpdateByExampleIncludeElement(introspectedTable));
document.getRootElement().addElement(logicalDeleteByExample);
// 2. 判断是否有主键,生成主键删除方法
if (introspectedTable.hasPrimaryKeyColumns()){
XmlElement logicalDeleteByPrimaryKey = new XmlElement("update"); //$NON-NLS-1$
logicalDeleteByPrimaryKey.addAttribute(new Attribute("id", METHOD_LOGICAL_DELETE_BY_PRIMARY_KEY));
String parameterClass;
if (introspectedTable.getRules().generatePrimaryKeyClass()) {
parameterClass = introspectedTable.getPrimaryKeyType();
} else {
// PK fields are in the base class. If more than on PK
// field, then they are coming in a map.
if (introspectedTable.getPrimaryKeyColumns().size() > 1) {
parameterClass = "map"; //$NON-NLS-1$
} else {
parameterClass = introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType().toString();
}
}
logicalDeleteByPrimaryKey.addAttribute(new Attribute("parameterType", parameterClass));
CommentTools.addComment(logicalDeleteByPrimaryKey);
StringBuilder sb1 = new StringBuilder();
sb1.append("update "); //$NON-NLS-1$
sb1.append(introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime());
sb1.append(" set ");
// 更新逻辑删除字段
sb1.append(this.logicalDeleteColumn.getActualColumnName());
sb1.append(" = ");
// 判断字段类型
JDBCType type1 = JDBCType.valueOf(this.logicalDeleteColumn.getJdbcType());
if (this.logicalDeleteValue == null || "NULL".equalsIgnoreCase(this.logicalDeleteValue)){
sb1.append("NULL");
} else if (JDBCType.CHAR == type1
|| JDBCType.LONGNVARCHAR == type1
|| JDBCType.LONGVARCHAR == type1
|| JDBCType.NCHAR == type1
|| JDBCType.NVARCHAR == type1
|| JDBCType.VARCHAR == type1){
sb1.append("'");
sb1.append(this.logicalDeleteValue);
sb1.append("'");
} else {
sb1.append(this.logicalDeleteValue);
}
logicalDeleteByPrimaryKey.addElement(new TextElement(sb1.toString()));
boolean and = false;
for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) {
sb.setLength(0);
if (and) {
sb.append(" and "); //$NON-NLS-1$
} else {
sb.append("where "); //$NON-NLS-1$
and = true;
}
sb.append(MyBatis3FormattingUtilities.getEscapedColumnName(introspectedColumn));
sb.append(" = "); //$NON-NLS-1$
sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn));
logicalDeleteByPrimaryKey.addElement(new TextElement(sb.toString()));
}
document.getRootElement().addElement(logicalDeleteByPrimaryKey);
}
}
return true;
}
/**
* Model 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (this.logicalDeleteColumn != null){
// 添加删除标志位常量
Field field = new Field(DEL_FLAG_NAME, this.logicalDeleteColumn.getFullyQualifiedJavaType());
field.setVisibility(JavaVisibility.PUBLIC);
field.setStatic(true);
field.setFinal(true);
if (this.logicalDeleteValue == null || "NULL".equalsIgnoreCase(this.logicalDeleteValue)){
field.setInitializationString("null");
} else if (this.logicalDeleteColumn.getFullyQualifiedJavaType().getShortNameWithoutTypeArguments().equalsIgnoreCase("String")){
field.setInitializationString("\"" + this.logicalDeleteValue + "\"");
} else if (this.logicalDeleteColumn.getFullyQualifiedJavaType().getShortNameWithoutTypeArguments().equalsIgnoreCase("Boolean")){
field.setInitializationString((this.logicalDeleteValue.equals("1") || this.logicalDeleteValue.equalsIgnoreCase("true")) ? "true" : "false");
} else {
field.setInitializationString(this.logicalDeleteValue);
}
CommentTools.addFieldComment(field, introspectedTable);
// 常量插入到第一位
ArrayList<Field> fields = (ArrayList<Field>) topLevelClass.getFields();
fields.add(0, field);
}
return true;
}
/**
* ModelExample Methods 生成
* 具体执行顺序 http://www.mybatis.org/generator/reference/pluggingIn.html
*
* @param topLevelClass
* @param introspectedTable
* @return
*/
@Override
public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (this.logicalDeleteColumn != null){
// 引入 Model类
FullyQualifiedJavaType model = introspectedTable.getRules().calculateAllFieldsClass();
topLevelClass.addImportedType(model);
List<InnerClass> innerClasses = topLevelClass.getInnerClasses();
for (InnerClass innerClass : innerClasses) {
if ("Criteria".equals(innerClass.getType().getShortName())) {
// 增加逻辑删除条件
Method method = new Method(METHOD_LOGICAL_DELETE);
CommentTools.addGeneralMethodComment(method, introspectedTable);
method.setVisibility(JavaVisibility.PUBLIC);
method.setReturnType(innerClass.getType());
method.addParameter(new Parameter(FullyQualifiedJavaType.getBooleanPrimitiveInstance(), "deleted"));
StringBuffer sb = new StringBuffer();
sb.append("return deleted ? ");
String modelName = model.getShortName();
// 调用EqualTo方法
StringBuilder equalToMethodName = new StringBuilder();
equalToMethodName.append(this.logicalDeleteColumn.getJavaProperty());
equalToMethodName.setCharAt(0, Character.toUpperCase(equalToMethodName.charAt(0)));
equalToMethodName.insert(0, "and"); //$NON-NLS-1$
equalToMethodName.append("EqualTo");
sb.append(equalToMethodName);
sb.append("("+modelName + "." + DEL_FLAG_NAME + ")");
sb.append(" : ");
// 调用NotEqualTo 方法
StringBuilder notEqualToMethodName = new StringBuilder();
notEqualToMethodName.append(this.logicalDeleteColumn.getJavaProperty());
notEqualToMethodName.setCharAt(0, Character.toUpperCase(notEqualToMethodName.charAt(0)));
notEqualToMethodName.insert(0, "and"); //$NON-NLS-1$
notEqualToMethodName.append("NotEqualTo");
sb.append(notEqualToMethodName);
sb.append("("+modelName + "." + DEL_FLAG_NAME + ")");
sb.append(";");
method.addBodyLine(sb.toString());
innerClass.addMethod(method);
}
}
}
return true;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2014.
* 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.
@@ -22,6 +22,7 @@ import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.internal.util.JavaBeansUtil;
import org.mybatis.generator.internal.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -42,7 +43,13 @@ public class ModelBuilderPlugin extends PluginAdapter {
/**
* {@inheritDoc}
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是targetRuntime为MyBatis3
if (StringUtility.stringHasValue(getContext().getTargetRuntime()) && "MyBatis3".equalsIgnoreCase(getContext().getTargetRuntime()) == false ){
logger.warn("itfsw:插件"+this.getClass().getTypeName()+"要求运行targetRuntime必须为MyBatis3!");
return false;
}
return true;
}
@@ -63,7 +70,7 @@ public class ModelBuilderPlugin extends PluginAdapter {
innerClass.setVisibility(JavaVisibility.PUBLIC);
innerClass.setStatic(true);
CommentTools.addClassComment(innerClass, introspectedTable);
logger.info("itfsw:生成内部Builder类");
logger.debug("itfsw:生成内部Builder类");
// 构建内部obj变量
Field f = new Field("obj", topLevelClass.getType());
@@ -77,7 +84,7 @@ public class ModelBuilderPlugin extends PluginAdapter {
constructor.addBodyLine(new StringBuilder("this.obj = new ")
.append(topLevelClass.getType().getShortName()).append("();").toString());
innerClass.addMethod(constructor);
logger.info("itfsw:生成内部Builder类构造方法");
logger.debug("itfsw:生成内部Builder类构造方法");
// !!可能Model存在复合主键情况,字段要加上这些
if (topLevelClass.getSuperClass() != null && topLevelClass.getSuperClass().compareTo(new FullyQualifiedJavaType(introspectedTable.getPrimaryKeyType())) == 0){
@@ -94,7 +101,7 @@ public class ModelBuilderPlugin extends PluginAdapter {
method.addBodyLine(new StringBuilder().append("return this;").toString());
CommentTools.addGeneralMethodComment(method, introspectedTable);
innerClass.addMethod(method);
logger.info("itfsw:生成内部Builder类的复合主键字段对应方法"+field.getName());
logger.debug("itfsw:生成内部Builder类的复合主键字段对应方法"+field.getName());
}
}
@@ -112,7 +119,7 @@ public class ModelBuilderPlugin extends PluginAdapter {
method.addBodyLine(new StringBuilder().append("return this;").toString());
CommentTools.addGeneralMethodComment(method, introspectedTable);
innerClass.addMethod(method);
logger.info("itfsw:生成内部Builder类的普通字段对应方法"+field.getName());
logger.debug("itfsw:生成内部Builder类的普通字段对应方法"+field.getName());
}
Method build = new Method("build");
@@ -121,7 +128,7 @@ public class ModelBuilderPlugin extends PluginAdapter {
build.addBodyLine("return this.obj;");
CommentTools.addGeneralMethodComment(build, introspectedTable);
innerClass.addMethod(build);
logger.info("itfsw:生成内部Builder类的build方法");
logger.debug("itfsw:生成内部Builder类的build方法");
topLevelClass.addInnerClass(innerClass);
return true;
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2014.
* 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.
@@ -25,6 +25,7 @@ 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.internal.util.StringUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -49,6 +50,11 @@ public class SelectOneByExamplePlugin extends PluginAdapter {
*/
@Override
public boolean validate(List<String> warnings) {
// 插件使用前提是targetRuntime为MyBatis3
if (StringUtility.stringHasValue(getContext().getTargetRuntime()) && "MyBatis3".equalsIgnoreCase(getContext().getTargetRuntime()) == false ){
logger.warn("itfsw:插件"+this.getClass().getTypeName()+"要求运行targetRuntime必须为MyBatis3!");
return false;
}
return true;
}
@@ -63,11 +69,11 @@ public class SelectOneByExamplePlugin extends PluginAdapter {
*/
@Override
public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
logger.info("itfsw:生成"+interfaze.getType()+"对应SelectOneByExample方法...");
logger.debug("itfsw:生成"+interfaze.getType()+"对应SelectOneByExample方法...");
// 方法生成
Method method = new Method(METHOD_NAME);
// 方法可见性
method.setVisibility(JavaVisibility.PUBLIC);
// 方法可见性 interface会忽略
// method.setVisibility(JavaVisibility.PUBLIC);
// 返回值类型
FullyQualifiedJavaType returnType = introspectedTable.getRules().calculateAllFieldsClass();
method.setReturnType(returnType);
@@ -92,7 +98,7 @@ public class SelectOneByExamplePlugin extends PluginAdapter {
*/
@Override
public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
logger.info("itfsw:生成表"+introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()+"("+ (introspectedTable.hasBLOBColumns() ? "有" : "无")+"Blob类型)的mapping.xml对应SelectOneByExample方法...");
logger.debug("itfsw:生成表"+introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()+"("+ (introspectedTable.hasBLOBColumns() ? "有" : "无")+"Blob类型)的mapping.xml对应SelectOneByExample方法...");
//数据库表名
String tableName = introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime();
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2014.
* 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.
@@ -19,6 +19,7 @@ package com.itfsw.mybatis.generator.plugins.utils;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
@@ -111,4 +112,24 @@ public class CommentTools {
xmlElement.addElement(new TextElement("-->")); //$NON-NLS-1$
}
/**
* 生成通用接口注解
*
* @param interf 接口
* @param introspectedTable 表
*/
public static void addInterfaceComment(Interface interf, IntrospectedTable introspectedTable) {
StringBuilder sb = new StringBuilder();
interf.addJavaDocLine("/**"); //$NON-NLS-1$
interf.addJavaDocLine(" * 这是Mybatis Generator拓展插件生成的接口(请勿删除)."); //$NON-NLS-1$
sb.append(" * This class corresponds to the database table "); //$NON-NLS-1$
sb.append(introspectedTable.getFullyQualifiedTable());
interf.addJavaDocLine(sb.toString());
interf.addJavaDocLine(" *");
interf.addJavaDocLine(" * "+MergeConstants.NEW_ELEMENT_TAG);
interf.addJavaDocLine(" * @author hewei");
interf.addJavaDocLine(" */"); //$NON-NLS-1$
}
}
@@ -0,0 +1,140 @@
/*
*
* * 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;
import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.java.*;
import java.util.Iterator;
import java.util.Set;
import static org.mybatis.generator.api.dom.OutputUtilities.*;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
/**
* ---------------------------------------------------------------------------
* 内部接口
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/1/12 17:53
* ---------------------------------------------------------------------------
*/
public class InnerInterface extends Interface{
public InnerInterface(FullyQualifiedJavaType type) {
super(type);
}
public InnerInterface(String type) {
super(type);
}
/**
* 格式化后内容,因为是内部接口,需要增加缩进
*
* @param indentLevel the indent level
* @param compilationUnit the compilation unit
* @return the formatted content
*/
public String getFormattedContent(int indentLevel, CompilationUnit compilationUnit) {
StringBuilder sb = new StringBuilder();
for (String commentLine : getFileCommentLines()) {
sb.append(commentLine);
newLine(sb);
}
if (stringHasValue(getType().getPackageName())) {
sb.append("package "); //$NON-NLS-1$
sb.append(getType().getPackageName());
sb.append(';');
newLine(sb);
newLine(sb);
}
for (String staticImport : getStaticImports()) {
sb.append("import static "); //$NON-NLS-1$
sb.append(staticImport);
sb.append(';');
newLine(sb);
}
if (getStaticImports().size() > 0) {
newLine(sb);
}
Set<String> importStrings = calculateImports(getImportedTypes());
for (String importString : importStrings) {
sb.append(importString);
newLine(sb);
}
if (importStrings.size() > 0) {
newLine(sb);
}
addFormattedJavadoc(sb, indentLevel);
addFormattedAnnotations(sb, indentLevel);
OutputUtilities.javaIndent(sb, indentLevel);
sb.append(getVisibility().getValue());
if (isFinal()) {
sb.append("final "); //$NON-NLS-1$
}
sb.append("interface "); //$NON-NLS-1$
sb.append(getType().getShortName());
if (getSuperInterfaceTypes().size() > 0) {
sb.append(" extends "); //$NON-NLS-1$
boolean comma = false;
for (FullyQualifiedJavaType fqjt : getSuperInterfaceTypes()) {
if (comma) {
sb.append(", "); //$NON-NLS-1$
} else {
comma = true;
}
sb.append(JavaDomUtils.calculateTypeName(this, fqjt));
}
}
sb.append(" {"); //$NON-NLS-1$
indentLevel++;
Iterator<Method> mtdIter = getMethods().iterator();
while (mtdIter.hasNext()) {
newLine(sb);
Method method = mtdIter.next();
sb.append(method.getFormattedContent(indentLevel, true, this));
if (mtdIter.hasNext()) {
newLine(sb);
}
}
indentLevel--;
newLine(sb);
javaIndent(sb, indentLevel);
sb.append('}');
return sb.toString();
}
}
@@ -0,0 +1,61 @@
/*
*
* * 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;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.InnerClass;
/**
* ---------------------------------------------------------------------------
* 把InnerInterface包装成InnerClass(Mybatis Generator 没有提供内部接口实现)
* ---------------------------------------------------------------------------
* @author: hewei
* @time:2017/1/12 17:40
* ---------------------------------------------------------------------------
*/
public class InnerInterfaceWrapperToInnerClass extends InnerClass{
private InnerInterface innerInterface; // 内部接口
public InnerInterfaceWrapperToInnerClass(FullyQualifiedJavaType type) {
super(type);
}
public InnerInterfaceWrapperToInnerClass(String typeName) {
super(typeName);
}
public InnerInterfaceWrapperToInnerClass(InnerInterface innerInterface){
super(innerInterface.getType());
this.innerInterface = innerInterface;
}
/**
* 重写获取Java内容方法,调用InnerInterface的实现
*
* @param indentLevel
* @param compilationUnit
* @return
*/
@Override
public String getFormattedContent(int indentLevel, CompilationUnit compilationUnit) {
return this.innerInterface.getFormattedContent(indentLevel, compilationUnit);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright (c) 2014.
* 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.