目的:
- 生成的mapper方法名太长、我想改成自己的风格
- 实体类集成lombok插件,省去大量get、set方法
- 生成日期格式化代码:
@JsonFormat(locale = "zh", timezone = "Asia/Shanghai", pattern = "yyyy-MM-dd HH:mm:ss")
- 实体类集成swagger,自动生成API文档
- 某些
<if test="remark != null">
等判断中缺失remark != ''
判断(要试自己情况决定是否使用)
实操
引入Maven依赖,添加generatorConfig.xml
文件省略
自定义LombokPlugin
:
package com.cong.config;
import lombok.extern.slf4j.Slf4j;
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.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.XmlElement;
import java.util.List;
@Slf4j
public class LombokPlugin extends PluginAdapter {
@Override
public boolean validate(List<String> warnings) {
return true;
}
@Override
public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
introspectedTable.setSelectByPrimaryKeyStatementId("detail");// 详情接口方法名
introspectedTable.setDeleteByPrimaryKeyStatementId("delete");// 删除接口方法名
introspectedTable.setUpdateByPrimaryKeySelectiveStatementId("update");// 更新接口方法名
topLevelClass.addImportedType("lombok.Data");// lombok
topLevelClass.addImportedType("lombok.NoArgsConstructor");// lombok
topLevelClass.addImportedType("io.swagger.annotations.ApiModelProperty");// swagger
topLevelClass.addImportedType("io.swagger.annotations.ApiModel");// swagger
topLevelClass.addAnnotation("@Data");// lombok
topLevelClass.addAnnotation("@ApiModel(" + "\"替换区\"" + ")");// lombok
topLevelClass.addAnnotation("@NoArgsConstructor");// lombok
List<IntrospectedColumn> allColumns = introspectedTable.getAllColumns();
for (IntrospectedColumn column : allColumns) {
if (column.getJdbcTypeName().equals("TIMESTAMP")) {
topLevelClass.addImportedType("com.fasterxml.jackson.annotation.JsonFormat");// 日期序列化
return true;
}
}
return true;
}
@Override
public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
return false;
}
@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
return false;
}
@Override
public boolean sqlMapInsertSelectiveElementGenerated(XmlElement element, IntrospectedTable introspectedTable) {
return true;
}
}
- 引入包
- 添加注解
- 修改接口名
自定义注释生成器MybatisCommentGenerator
package com.cong.config;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.generator.api.CommentGenerator;
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.XmlElement;
import java.util.Properties;
@Slf4j
public class MybatisCommentGenerator implements CommentGenerator {
private Properties properties = new Properties();
private boolean suppressAllComments = true;
private boolean addRemarkComments = true;
public MybatisCommentGenerator() {
}
public void addJavaFileComment(CompilationUnit compilationUnit) {
}
/**
* Mybatis的Mapper.xml文件里面的注释
*/
public void addComment(XmlElement xmlElement) {
}
public void addRootComment(XmlElement rootElement) {
log.info("addRootComment");
}
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
this.suppressAllComments = false;
this.addRemarkComments = true;
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
log.info("addClassComment");
}
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
log.info("addModelClassComment");
}
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
if (!this.suppressAllComments) {
// swagger
field.addAnnotation("@ApiModelProperty(\"" + introspectedColumn.getRemarks() + "\")");
if (introspectedColumn.getJdbcTypeName().equals("TIMESTAMP")) {
// 时间类型的自动加上日期format
field.addAnnotation("@JsonFormat(locale = \"zh\", timezone = \"Asia/Shanghai\", pattern = \"yyyy-MM-dd HH:mm:ss\")");
}
}
}
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
}
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
}
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
log.info("addClassComment1");
}
}
自定义xml代码生成器
-
MyJavaMapperGenerator:
package com.cong.config; import org.mybatis.generator.api.CommentGenerator; import org.mybatis.generator.api.dom.java.CompilationUnit; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; import org.mybatis.generator.api.dom.java.Interface; import org.mybatis.generator.api.dom.java.JavaVisibility; import org.mybatis.generator.codegen.AbstractXmlGenerator; import org.mybatis.generator.codegen.mybatis3.javamapper.JavaMapperGenerator; import org.mybatis.generator.config.PropertyRegistry; import java.util.ArrayList; import java.util.List; import static org.mybatis.generator.internal.util.StringUtility.stringHasValue; import static org.mybatis.generator.internal.util.messages.Messages.getString; public class MyJavaMapperGenerator extends JavaMapperGenerator { public MyJavaMapperGenerator() { super(true); } public MyJavaMapperGenerator(boolean requiresMatchedXMLGenerator) { super(requiresMatchedXMLGenerator); } @Override public List<CompilationUnit> getCompilationUnits() { progressCallback.startTask(getString("Progress.17", //$NON-NLS-1$ introspectedTable.getFullyQualifiedTable().toString())); CommentGenerator commentGenerator = context.getCommentGenerator(); FullyQualifiedJavaType type = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaMapperType()); Interface interfaze = new Interface(type); interfaze.setVisibility(JavaVisibility.PUBLIC); commentGenerator.addJavaFileComment(interfaze); String rootInterface = introspectedTable.getTableConfigurationProperty(PropertyRegistry.ANY_ROOT_INTERFACE); if (!stringHasValue(rootInterface)) { rootInterface = context.getJavaClientGeneratorConfiguration().getProperty(PropertyRegistry.ANY_ROOT_INTERFACE); } if (stringHasValue(rootInterface)) { FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(rootInterface); interfaze.addSuperInterface(fqjt); interfaze.addImportedType(fqjt); } addCountByExampleMethod(interfaze); addDeleteByExampleMethod(interfaze); addDeleteByPrimaryKeyMethod(interfaze); addInsertMethod(interfaze); addInsertSelectiveMethod(interfaze); addSelectByExampleWithBLOBsMethod(interfaze); addSelectByExampleWithoutBLOBsMethod(interfaze); addSelectByPrimaryKeyMethod(interfaze); addUpdateByExampleSelectiveMethod(interfaze); addUpdateByExampleWithBLOBsMethod(interfaze); addUpdateByExampleWithoutBLOBsMethod(interfaze); addUpdateByPrimaryKeySelectiveMethod(interfaze); addUpdateByPrimaryKeyWithBLOBsMethod(interfaze); addUpdateByPrimaryKeyWithoutBLOBsMethod(interfaze); List<CompilationUnit> answer = new ArrayList<CompilationUnit>(); if (context.getPlugins().clientGenerated(interfaze, null, introspectedTable)) { answer.add(interfaze); } List<CompilationUnit> extraCompilationUnits = getExtraCompilationUnits(); if (extraCompilationUnits != null) { answer.addAll(extraCompilationUnits); } return answer; } public List<CompilationUnit> getExtraCompilationUnits() { return null; } @Override public AbstractXmlGenerator getMatchedXMLGenerator() { return new MyXMLMapperGenerator(); } }
生效的在最后,使用自定义的xml生成器
-
MyXMLMapperGenerator:
package com.cong.config; import org.mybatis.generator.api.FullyQualifiedTable; import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.Document; import org.mybatis.generator.api.dom.xml.XmlElement; import org.mybatis.generator.codegen.AbstractXmlGenerator; import org.mybatis.generator.codegen.XmlConstants; import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.*; import static org.mybatis.generator.internal.util.messages.Messages.getString; public class MyXMLMapperGenerator extends AbstractXmlGenerator { public MyXMLMapperGenerator() { super(); } protected XmlElement getSqlMapElement() { FullyQualifiedTable table = introspectedTable.getFullyQualifiedTable(); progressCallback.startTask(getString( "Progress.12", table.toString())); //$NON-NLS-1$ XmlElement answer = new XmlElement("mapper"); //$NON-NLS-1$ String namespace = introspectedTable.getMyBatis3SqlMapNamespace(); answer.addAttribute(new Attribute("namespace", //$NON-NLS-1$ namespace)); context.getCommentGenerator().addRootComment(answer); addResultMapWithoutBLOBsElement(answer); addResultMapWithBLOBsElement(answer); addExampleWhereClauseElement(answer); addMyBatis3UpdateByExampleWhereClauseElement(answer); addBaseColumnListElement(answer); addBlobColumnListElement(answer); addSelectByExampleWithBLOBsElement(answer); addSelectByExampleWithoutBLOBsElement(answer); addSelectByPrimaryKeyElement(answer); addDeleteByPrimaryKeyElement(answer); addDeleteByExampleElement(answer); addInsertElement(answer); addInsertSelectiveElement(answer); addCountByExampleElement(answer); addUpdateByExampleSelectiveElement(answer); addUpdateByExampleWithBLOBsElement(answer); addUpdateByExampleWithoutBLOBsElement(answer); addUpdateByPrimaryKeySelectiveElement(answer); addUpdateByPrimaryKeyWithBLOBsElement(answer); addUpdateByPrimaryKeyWithoutBLOBsElement(answer); return answer; } protected void addResultMapWithoutBLOBsElement(XmlElement parentElement) { if (introspectedTable.getRules().generateBaseResultMap()) { AbstractXmlElementGenerator elementGenerator = new ResultMapWithoutBLOBsElementGenerator(false); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addResultMapWithBLOBsElement(XmlElement parentElement) { if (introspectedTable.getRules().generateResultMapWithBLOBs()) { AbstractXmlElementGenerator elementGenerator = new ResultMapWithBLOBsElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addExampleWhereClauseElement(XmlElement parentElement) { if (introspectedTable.getRules().generateSQLExampleWhereClause()) { AbstractXmlElementGenerator elementGenerator = new ExampleWhereClauseElementGenerator( false); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addMyBatis3UpdateByExampleWhereClauseElement( XmlElement parentElement) { if (introspectedTable.getRules() .generateMyBatis3UpdateByExampleWhereClause()) { AbstractXmlElementGenerator elementGenerator = new ExampleWhereClauseElementGenerator( true); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addBaseColumnListElement(XmlElement parentElement) { if (introspectedTable.getRules().generateBaseColumnList()) { AbstractXmlElementGenerator elementGenerator = new BaseColumnListElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addBlobColumnListElement(XmlElement parentElement) { if (introspectedTable.getRules().generateBlobColumnList()) { AbstractXmlElementGenerator elementGenerator = new BlobColumnListElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addSelectByExampleWithoutBLOBsElement( XmlElement parentElement) { if (introspectedTable.getRules().generateSelectByExampleWithoutBLOBs()) { AbstractXmlElementGenerator elementGenerator = new SelectByExampleWithoutBLOBsElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addSelectByExampleWithBLOBsElement(XmlElement parentElement) { if (introspectedTable.getRules().generateSelectByExampleWithBLOBs()) { AbstractXmlElementGenerator elementGenerator = new SelectByExampleWithBLOBsElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addSelectByPrimaryKeyElement(XmlElement parentElement) { if (introspectedTable.getRules().generateSelectByPrimaryKey()) { AbstractXmlElementGenerator elementGenerator = new SelectByPrimaryKeyElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addDeleteByExampleElement(XmlElement parentElement) { if (introspectedTable.getRules().generateDeleteByExample()) { AbstractXmlElementGenerator elementGenerator = new DeleteByExampleElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addDeleteByPrimaryKeyElement(XmlElement parentElement) { if (introspectedTable.getRules().generateDeleteByPrimaryKey()) { AbstractXmlElementGenerator elementGenerator = new DeleteByPrimaryKeyElementGenerator(false); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addInsertElement(XmlElement parentElement) { if (introspectedTable.getRules().generateInsert()) { AbstractXmlElementGenerator elementGenerator = new InsertElementGenerator(false); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addInsertSelectiveElement(XmlElement parentElement) { if (introspectedTable.getRules().generateInsertSelective()) { AbstractXmlElementGenerator elementGenerator = new MyInsertSelectiveElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addCountByExampleElement(XmlElement parentElement) { if (introspectedTable.getRules().generateCountByExample()) { AbstractXmlElementGenerator elementGenerator = new CountByExampleElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addUpdateByExampleSelectiveElement(XmlElement parentElement) { if (introspectedTable.getRules().generateUpdateByExampleSelective()) { AbstractXmlElementGenerator elementGenerator = new UpdateByExampleSelectiveElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addUpdateByExampleWithBLOBsElement(XmlElement parentElement) { if (introspectedTable.getRules().generateUpdateByExampleWithBLOBs()) { AbstractXmlElementGenerator elementGenerator = new UpdateByExampleWithBLOBsElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addUpdateByExampleWithoutBLOBsElement( XmlElement parentElement) { if (introspectedTable.getRules().generateUpdateByExampleWithoutBLOBs()) { AbstractXmlElementGenerator elementGenerator = new UpdateByExampleWithoutBLOBsElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addUpdateByPrimaryKeySelectiveElement( XmlElement parentElement) { if (introspectedTable.getRules().generateUpdateByPrimaryKeySelective()) { AbstractXmlElementGenerator elementGenerator = new MyUpdateByPrimaryKeySelectiveElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addUpdateByPrimaryKeyWithBLOBsElement( XmlElement parentElement) { if (introspectedTable.getRules().generateUpdateByPrimaryKeyWithBLOBs()) { AbstractXmlElementGenerator elementGenerator = new UpdateByPrimaryKeyWithBLOBsElementGenerator(); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void addUpdateByPrimaryKeyWithoutBLOBsElement( XmlElement parentElement) { if (introspectedTable.getRules() .generateUpdateByPrimaryKeyWithoutBLOBs()) { AbstractXmlElementGenerator elementGenerator = new UpdateByPrimaryKeyWithoutBLOBsElementGenerator(false); initializeAndExecuteGenerator(elementGenerator, parentElement); } } protected void initializeAndExecuteGenerator( AbstractXmlElementGenerator elementGenerator, XmlElement parentElement) { elementGenerator.setContext(context); elementGenerator.setIntrospectedTable(introspectedTable); elementGenerator.setProgressCallback(progressCallback); elementGenerator.setWarnings(warnings); elementGenerator.addElements(parentElement); } @Override public Document getDocument() { Document document = new Document( XmlConstants.MYBATIS3_MAPPER_PUBLIC_ID, XmlConstants.MYBATIS3_MAPPER_SYSTEM_ID); document.setRootElement(getSqlMapElement()); if (!context.getPlugins().sqlMapDocumentGenerated(document, introspectedTable)) { document = null; } return document; } }
覆盖
addUpdateByPrimaryKeySelectiveElement
以及addInsertSelectiveElement
方法,具体的可以根据自己的习惯进行选择,调用的实现类参考系统默认的实现类编写,稍微修改即可,具体代码不解释了。 -
MyInsertSelectiveElementGenerator:
package com.cong.config; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType; 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.codegen.mybatis3.MyBatis3FormattingUtilities; import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator; import org.mybatis.generator.config.GeneratedKey; public class MyInsertSelectiveElementGenerator extends AbstractXmlElementGenerator { public MyInsertSelectiveElementGenerator() { super(); } @Override public void addElements(XmlElement parentElement) { XmlElement answer = new XmlElement("insert"); //$NON-NLS-1$ answer.addAttribute(new Attribute( "id", introspectedTable.getInsertSelectiveStatementId())); //$NON-NLS-1$ FullyQualifiedJavaType parameterType = introspectedTable.getRules() .calculateAllFieldsClass(); answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$ parameterType.getFullyQualifiedName())); context.getCommentGenerator().addComment(answer); 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) { if (gk.isJdbcStandard()) { answer.addAttribute(new Attribute("useGeneratedKeys", "true")); //$NON-NLS-1$ //$NON-NLS-2$ answer.addAttribute(new Attribute("keyProperty", introspectedColumn.getJavaProperty())); //$NON-NLS-1$ answer.addAttribute(new Attribute("keyColumn", introspectedColumn.getActualColumnName())); //$NON-NLS-1$ } else { answer.addElement(getSelectKey(introspectedColumn, gk)); } } } StringBuilder sb = new StringBuilder(); sb.append("insert into "); //$NON-NLS-1$ sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime()); answer.addElement(new TextElement(sb.toString())); XmlElement insertTrimElement = new XmlElement("trim"); //$NON-NLS-1$ insertTrimElement.addAttribute(new Attribute("prefix", "(")); //$NON-NLS-1$ //$NON-NLS-2$ insertTrimElement.addAttribute(new Attribute("suffix", ")")); //$NON-NLS-1$ //$NON-NLS-2$ insertTrimElement.addAttribute(new Attribute("suffixOverrides", ",")); //$NON-NLS-1$ //$NON-NLS-2$ answer.addElement(insertTrimElement); XmlElement valuesTrimElement = new XmlElement("trim"); //$NON-NLS-1$ valuesTrimElement.addAttribute(new Attribute("prefix", "values (")); //$NON-NLS-1$ //$NON-NLS-2$ valuesTrimElement.addAttribute(new Attribute("suffix", ")")); //$NON-NLS-1$ //$NON-NLS-2$ valuesTrimElement.addAttribute(new Attribute("suffixOverrides", ",")); //$NON-NLS-1$ //$NON-NLS-2$ answer.addElement(valuesTrimElement); for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) { if (MyBatis3FormattingUtilities .getEscapedColumnName(introspectedColumn).equals("status") || MyBatis3FormattingUtilities .getEscapedColumnName(introspectedColumn).equals("status_time")) { continue; } if (introspectedColumn.isSequenceColumn() || introspectedColumn.getFullyQualifiedJavaType().isPrimitive()) { // if it is a sequence column, it is not optional // This is required for MyBatis3 because MyBatis3 parses // and calculates the SQL before executing the selectKey // if it is primitive, we cannot do a null check sb.setLength(0); sb.append(MyBatis3FormattingUtilities .getEscapedColumnName(introspectedColumn)); sb.append(','); insertTrimElement.addElement(new TextElement(sb.toString())); sb.setLength(0); sb.append(MyBatis3FormattingUtilities .getParameterClause(introspectedColumn)); sb.append(','); valuesTrimElement.addElement(new TextElement(sb.toString())); continue; } XmlElement insertNotNullElement = new XmlElement("if"); //$NON-NLS-1$ sb.setLength(0); sb.append(introspectedColumn.getJavaProperty()); sb.append(" != null"); //$NON-NLS-1$ if (introspectedColumn.getJdbcTypeName().equals("VARCHAR") || introspectedColumn.getJdbcTypeName().equals("CHAR")) { sb.append(" and "); sb.append(introspectedColumn.getJavaProperty()); sb.append(" != ''"); } insertNotNullElement.addAttribute(new Attribute( "test", sb.toString())); //$NON-NLS-1$ sb.setLength(0); sb.append(MyBatis3FormattingUtilities .getEscapedColumnName(introspectedColumn)); sb.append(','); insertNotNullElement.addElement(new TextElement(sb.toString())); insertTrimElement.addElement(insertNotNullElement); XmlElement valuesNotNullElement = new XmlElement("if"); //$NON-NLS-1$ sb.setLength(0); sb.append(introspectedColumn.getJavaProperty()); sb.append(" != null"); //$NON-NLS-1$ if (introspectedColumn.getJdbcTypeName().equals("VARCHAR") || introspectedColumn.getJdbcTypeName().equals("CHAR")) { sb.append(" and "); sb.append(introspectedColumn.getJavaProperty()); sb.append(" != ''"); } valuesNotNullElement.addAttribute(new Attribute( "test", sb.toString())); //$NON-NLS-1$ sb.setLength(0); sb.append(MyBatis3FormattingUtilities .getParameterClause(introspectedColumn)); sb.append(','); valuesNotNullElement.addElement(new TextElement(sb.toString())); valuesTrimElement.addElement(valuesNotNullElement); } if (context.getPlugins().sqlMapInsertSelectiveElementGenerated( answer, introspectedTable)) { parentElement.addElement(answer); } } }
-
MyUpdateByPrimaryKeySelectiveElementGenerator:
package com.cong.config; import org.mybatis.generator.api.IntrospectedColumn; 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.codegen.mybatis3.MyBatis3FormattingUtilities; import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.AbstractXmlElementGenerator; public class MyUpdateByPrimaryKeySelectiveElementGenerator extends AbstractXmlElementGenerator { public MyUpdateByPrimaryKeySelectiveElementGenerator() { super(); } @Override public void addElements(XmlElement parentElement) { XmlElement answer = new XmlElement("update"); //$NON-NLS-1$ answer .addAttribute(new Attribute( "id", introspectedTable.getUpdateByPrimaryKeySelectiveStatementId())); //$NON-NLS-1$ String parameterType; if (introspectedTable.getRules().generateRecordWithBLOBsClass()) { parameterType = introspectedTable.getRecordWithBLOBsType(); } else { parameterType = introspectedTable.getBaseRecordType(); } answer.addAttribute(new Attribute("parameterType", //$NON-NLS-1$ parameterType)); context.getCommentGenerator().addComment(answer); StringBuilder sb = new StringBuilder(); sb.append("update "); //$NON-NLS-1$ sb.append(introspectedTable.getFullyQualifiedTableNameAtRuntime()); answer.addElement(new TextElement(sb.toString())); XmlElement dynamicElement = new XmlElement("set"); //$NON-NLS-1$ answer.addElement(dynamicElement); for (IntrospectedColumn introspectedColumn : introspectedTable.getNonPrimaryKeyColumns()) { if (MyBatis3FormattingUtilities .getEscapedColumnName(introspectedColumn).equals("status") || MyBatis3FormattingUtilities .getEscapedColumnName(introspectedColumn).equals("status_time")) { continue; } XmlElement isNotNullElement = new XmlElement("if"); //$NON-NLS-1$ sb.setLength(0); sb.append(introspectedColumn.getJavaProperty()); sb.append(" != null"); //$NON-NLS-1$ if (introspectedColumn.getJdbcTypeName().equals("VARCHAR") || introspectedColumn.getJdbcTypeName().equals("CHAR")){ sb.append(" and "); sb.append(introspectedColumn.getJavaProperty()); sb.append(" != ''"); } isNotNullElement.addAttribute(new Attribute("test", sb.toString())); //$NON-NLS-1$ dynamicElement.addElement(isNotNullElement); sb.setLength(0); sb.append(MyBatis3FormattingUtilities .getEscapedColumnName(introspectedColumn)); sb.append(" = "); //$NON-NLS-1$ sb.append(MyBatis3FormattingUtilities .getParameterClause(introspectedColumn)); sb.append(','); isNotNullElement.addElement(new TextElement(sb.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)); answer.addElement(new TextElement(sb.toString())); } if (context.getPlugins() .sqlMapUpdateByPrimaryKeySelectiveElementGenerated(answer, introspectedTable)) { parentElement.addElement(answer); } } }
上述两个类比较一下和默认实现不同的地方就懂了,我相信开始做这个事情的应该很简单就能看懂。
修改generatorConfig.xml
(重点)
<?xml version="1.0" encoding="UTF-8"?>
<!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="mybatis.yml"></properties>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 使用lombok插件 -->
<plugin type="com.cong.config.LombokPlugin">
<property name="hasLombok" value="true"/>
</plugin>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<!-- optional,旨在创建class时,对注释进行控制 -->
<commentGenerator type="com.cong.config.MybatisCommentGenerator">
<property name="suppressAllComments" value="false" />
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!--jdbc的数据库连接 -->
<jdbcConnection driverClass="${jdbc.driver-class-name}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}">
</jdbcConnection>
<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制 -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类 targetPackage 指定生成的model生成所在的包名
targetProject 指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="com.cong.ums.entity"
targetProject="${mybatis.entity}">
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="false" />
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="true" />
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法,使用lombok插件,不需要getter和setter -->
<!-- <property name="immutable" value="true" /> -->
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<!-- <property name="trimStrings" value="true" /> -->
</javaModelGenerator>
<!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
<sqlMapGenerator targetPackage="mapping"
targetProject="src/main/resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码 type="ANNOTATEDMAPPER",生成Java Model
和基于注解的Mapper对象 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 type="XMLMAPPER",生成SQLMap
XML文件和独立的Mapper接口 -->
<javaClientGenerator type="com.cong.config.MyJavaMapperGenerator"
targetPackage="com.cong.ams.mapper" targetProject="${mybatis.mapper}">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="ums_user" domainObjectName="UmsUser"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
详解:
- plugin
引入lombok插件,指定的类一定要继承PluginAdapter
- commentGenerator
注释,指定类实现CommentGenerator
即可,模仿DefaultCommentGenerator
默认实现编写即可 - javaClientGenerator
类生成器,我本来认为xml生成和comment一样自定义生成器即可,但是sqlMapGenerator
没有type标签,我仔细断点调试之后发现原来这个Generator
有好多默认实现,而且竟然是在JavaClientGenerator
里面定义的!!所以自定义MyJavaMapperGenerator
在这里面指定XMLMapperGenerator
,在javaClientGenerator
标签中再指定MyJavaMapperGenerator
,其实感觉是不太友好的。
补充
上述所有类需要提取出来单独做一个jar依赖,不要直接在当前项目中写上述代码。