mybatis(mysql)代码生成器扩展

前些天在做我的KSF框架的时候需要用到mybatis代码生成器,

但是发现有一些东西需要调整,主要集中在以下几点:

1. 加入batchInsert 

2. 加入batchUpdate

3. mysql字段名和关键字冲突问题

4. 生成的实体类继承基类

5. mapper继承基础接口,实现自己的代码

6. insert之后获取生成的ID

7. 使实体可序列化


 加入batchInsert 

1.在generatorConfig.xml中加入以下插件

2.在pom的mybatis-generator-maven-plugin中加入以下依赖


    com.itfsw
    mybatis-generator-plugin
    1.0.5

加入batchUpdate

1.在generatorConfig.xml中加入以下插件

2.编写插件代码

  1 package com.kuta.base.mybatis.plugins;
  2 
  3 import java.util.List;
  4 
  5 import org.mybatis.generator.api.IntrospectedColumn;
  6 import org.mybatis.generator.api.IntrospectedTable;
  7 import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
  8 import org.mybatis.generator.api.dom.java.Interface;
  9 import org.mybatis.generator.api.dom.java.TopLevelClass;
 10 import org.mybatis.generator.api.dom.xml.Document;
 11 import org.mybatis.generator.api.dom.xml.TextElement;
 12 import org.mybatis.generator.api.dom.xml.XmlElement;
 13 import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
 14 import org.mybatis.generator.config.MergeConstants;
 15 
 16 import com.kuta.base.database.util.SqlMapperGeneratorTool;
 17 
 18 public class KutaBatchUpdatePlugin extends org.mybatis.generator.api.PluginAdapter{
 19 
 20     private final static String BATCH_UPDATE = "batchUpdate";
 21 
 22     private final static String PARAMETER_NAME = "recordList";
 23 
 24 
 25     @Override
 26     public boolean validate(List list) {
 27         return true;
 28     }
 29 
 30     @Override
 31     public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
 32 
 33         if (introspectedTable.getTargetRuntime().equals(IntrospectedTable.TargetRuntime.MYBATIS3)) {
 34             MethodGeneratorTool.defaultBatchInsertOrUpdateMethodGen(MethodGeneratorTool.UPDATE, interfaze, introspectedTable, context);
 35         }
 36         return super.clientGenerated(interfaze, topLevelClass, introspectedTable);
 37     }
 38 
 39     @Override
 40     public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
 41         if (introspectedTable.getTargetRuntime().equals(IntrospectedTable.TargetRuntime.MYBATIS3)) {
 42             addSqlMapper(document, introspectedTable);
 43         }
 44         return super.sqlMapDocumentGenerated(document, introspectedTable);
 45     }
 46 
 47     public void addSqlMapper(Document document, IntrospectedTable introspectedTable) {
 48         String tableName = introspectedTable.getFullyQualifiedTableNameAtRuntime();
 49         List columnList = introspectedTable.getAllColumns();
 50         //primaryKey的JDBC名字
 51         String primaryKeyName = introspectedTable.getPrimaryKeyColumns().get(0).getActualColumnName();
 52 
 53         //primaryKey的JAVA变量
 54         String primaryKeyParameterClause = MyBatis3FormattingUtilities.getParameterClause(introspectedTable.getPrimaryKeyColumns().get(0), "item.");
 55 
 56         //primaryKey的JAVA名字
 57         String primaryKeyJavaName = introspectedTable.getPrimaryKeyColumns().get(0).getJavaProperty();
 58         
 59 
 60         XmlElement updateXmlElement = SqlMapperGeneratorTool.baseElementGenerator(SqlMapperGeneratorTool.UPDATE,
 61                 BATCH_UPDATE,
 62                 FullyQualifiedJavaType.getNewListInstance());
 63         updateXmlElement.addElement(new TextElement(""));
 65         updateXmlElement.addElement(new TextElement(String.format("update %s ", tableName)));
 66 
 67         XmlElement trimElement = SqlMapperGeneratorTool.baseTrimElement("set", null, ",");
 68 
 69         for (int i = 0; i < columnList.size(); i++) {
 70 
 71             IntrospectedColumn introspectedColumn = columnList.get(i);
 72 
 73             String columnName = introspectedColumn.getActualColumnName();
 74 
 75             String columnJavaTypeName = introspectedColumn.getJavaProperty("item.");
 76 
 77             String parameterClause = MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, "item.");
 78 
 79 
 80             if (introspectedColumn.isIdentity()) {
 81                 continue;
 82             }
 83 
 84             String ifSql = String.format("when %s then %s", primaryKeyParameterClause, parameterClause);
 85             XmlElement ifElement = SqlMapperGeneratorTool.baseIfJudgeElementGen(columnJavaTypeName, ifSql, false);
 86 
 87             String ifNullSql = String.format("when %s then %s", primaryKeyParameterClause, tableName + "." + columnName);
 88             XmlElement ifNullElement = SqlMapperGeneratorTool.baseIfJudgeElementGen(columnJavaTypeName, ifNullSql, true);
 89 
 90 
 91             XmlElement foreachElement = SqlMapperGeneratorTool.baseForeachElementGenerator(PARAMETER_NAME, "item", "index", null);
 92             foreachElement.addElement(ifElement);
 93             foreachElement.addElement(ifNullElement);
 94 
 95             XmlElement caseTrimElement = SqlMapperGeneratorTool.baseTrimElement(columnName + " =case " + primaryKeyName, "end,", null);
 96             caseTrimElement.addElement(foreachElement);
 97 
 98             trimElement.addElement(caseTrimElement);
 99         }
100 
101         updateXmlElement.addElement(trimElement);
102 
103         XmlElement foreachElement = SqlMapperGeneratorTool.baseForeachElementGenerator(PARAMETER_NAME,
104                 "item",
105                 "index",
106                 ",");
107         foreachElement.addElement(new TextElement(primaryKeyParameterClause));
108 
109         updateXmlElement.addElement(new TextElement(String.format("where %s in(", primaryKeyName)));
110 
111         updateXmlElement.addElement(foreachElement);
112 
113         updateXmlElement.addElement(new TextElement(")"));
114         
115         document.getRootElement().addElement(updateXmlElement);
116     }
117 
118     
119 
120     
121 
122 }
  1 package com.kuta.base.mybatis.plugins;
  2 
  3 import java.util.Set;
  4 import java.util.TreeSet;
  5 
  6 import org.mybatis.generator.api.CommentGenerator;
  7 import org.mybatis.generator.api.IntrospectedTable;
  8 import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
  9 import org.mybatis.generator.api.dom.java.Interface;
 10 import org.mybatis.generator.api.dom.java.JavaVisibility;
 11 import org.mybatis.generator.api.dom.java.Method;
 12 import org.mybatis.generator.api.dom.java.Parameter;
 13 import org.mybatis.generator.config.Context;
 14 
 15 public class MethodGeneratorTool {
 16     private final static String BATCH_INSERT = "batchInsert";
 17 
 18     private final static String PARAMETER_NAME = "recordList";
 19 
 20     private final static String DELETE_PARAMETER_NAME = "ids";
 21 
 22     private final static String BATCH_UPDATE = "batchUpdate";
 23 
 24     private final static String BATCH_DELETE = "batchDelete";
 25 
 26     public final static Integer INSERT = 0;
 27 
 28     public final static Integer UPDATE = 1;
 29     /**
 30      * java方法生成构造器.
 31      *
 32      * @param methodName     the method name
 33      * @param visibility     the visibility
 34      * @param returnJavaType the return java type
 35      * @param parameters     the parameters
 36      * @author HuWeihui
 37      * @since hui_project v1
 38      */
 39     public static Method methodGenerator(String methodName,
 40                                        JavaVisibility visibility,
 41                                        FullyQualifiedJavaType returnJavaType,
 42                                        Parameter... parameters) {
 43         Method method = new Method();
 44         method.setName(methodName);
 45         method.setVisibility(visibility);
 46         method.setReturnType(returnJavaType);
 47         for (Parameter parameter : parameters) {
 48             method.addParameter(parameter);
 49         }
 50         return method;
 51     }
 52 
 53     /**
 54      * 导入基础的java类型
 55      *
 56      * @param introspectedTable the introspected table
 57      * @return the set
 58      * @author HuWeihui
 59      * @since hui_project v1
 60      */
 61     public static Set importedBaseTypesGenerator(IntrospectedTable introspectedTable){
 62         //获取实体类类型
 63         FullyQualifiedJavaType parameterType = introspectedTable.getRules().calculateAllFieldsClass();
 64         //@Param需要导入的类型
 65         FullyQualifiedJavaType paramType = new FullyQualifiedJavaType("org.apache.ibatis.annotations.Param");
 66         //Integer类型
 67         FullyQualifiedJavaType intInstance = FullyQualifiedJavaType.getIntInstance();
 68         //List
 69         FullyQualifiedJavaType listParameterType = FullyQualifiedJavaType.getNewListInstance();
 70 
 71         Set importedTypes = new TreeSet();
 72         importedTypes.add(parameterType);
 73         importedTypes.add(intInstance);
 74         importedTypes.add(paramType);
 75         importedTypes.add(listParameterType);
 76         return importedTypes;
 77     }
 78 
 79     /**
 80      * 默认的批量新增/更新方法构造器.
 81      *
 82      * @param interfaze         the interfaze
 83      * @param introspectedTable the introspected table
 84      * @param context           the context
 85      * @author HuWeihui
 86      * @since hui_project v1
 87      */
 88     public static void defaultBatchInsertOrUpdateMethodGen(Integer type ,Interface interfaze,IntrospectedTable introspectedTable, Context context){
 89         //JAVA导入基础包
 90         Set importedTypes = MethodGeneratorTool.importedBaseTypesGenerator(introspectedTable);
 91 
 92         //List
 93         FullyQualifiedJavaType listParameterType = FullyQualifiedJavaType.getNewListInstance();
 94         listParameterType.addTypeArgument(introspectedTable.getRules().calculateAllFieldsClass());
 95 
 96         String methodName = BATCH_INSERT;
 97         //1.batchInsert
 98         if (type.equals(UPDATE)){
 99             methodName = BATCH_UPDATE;
100         }
101         Method insertMethod = MethodGeneratorTool.methodGenerator(methodName,
102                 JavaVisibility.DEFAULT,
103                 FullyQualifiedJavaType.getIntInstance(),
104                 new Parameter(listParameterType, PARAMETER_NAME, "@Param(\"" + PARAMETER_NAME + "\")"));
105 
106         CommentGenerator commentGenerator = context.getCommentGenerator();
107         commentGenerator.addGeneralMethodComment(insertMethod, introspectedTable);
108 
109         interfaze.addImportedTypes(importedTypes);
110         interfaze.addMethod(insertMethod);
111     }
112 
113     /**
114      * 默认的批量删除方法构造器.
115      *
116      * @param interfaze         the interfaze
117      * @param introspectedTable the introspected table
118      * @param context           the context
119      * @author HuWeihui
120      * @since hui_project v1
121      */
122     public static void defaultBatchDeleteMethodGen(Interface interfaze,IntrospectedTable introspectedTable, Context context){
123         //JAVA导入基础包
124         Set importedTypes = MethodGeneratorTool.importedBaseTypesGenerator(introspectedTable);
125         FullyQualifiedJavaType paramType = introspectedTable.getPrimaryKeyColumns().get(0).getFullyQualifiedJavaType();
126         Method batchDeleteMethod = MethodGeneratorTool.methodGenerator(BATCH_DELETE,
127                 JavaVisibility.DEFAULT,
128                 FullyQualifiedJavaType.getIntInstance(),
129                 new Parameter(new FullyQualifiedJavaType(paramType.getFullyQualifiedName()+"[]"), DELETE_PARAMETER_NAME, "@Param(\""+DELETE_PARAMETER_NAME+"\")"));
130 
131         context.getCommentGenerator().addGeneralMethodComment(batchDeleteMethod,introspectedTable);
132         interfaze.addImportedTypes(importedTypes);
133         interfaze.addMethod(batchDeleteMethod);
134     }
135 }

3. 在pom的mybatis-generator-maven-plugin中加入以上代码所在库的依赖

mysql字段名和关键字冲突问题

1.在generatorConfig.xml中加入以下属性配置


2. 在table节点加入delimitAllColumns="true"属性

生成的实体类继承基类

在generatorConfig.xml文件中的javaModelGenerator节点中加入以下属性配置

mapper继承基础接口,实现自己的代码

在generatorConfig.xml文件中的table节点加入以下属性配置

insert之后获取生成的ID

在generatorConfig.xml文件中的table节点加入以下属性配置

使实体可序列化

在generatorConfig.xml文件中加入以下属性配置

  

 

你可能感兴趣的:(mybatis(mysql)代码生成器扩展)