mybatis 逆向工程 自定义扩展Mapper.java和Mapper.xml

4 篇文章 0 订阅
本文档介绍了一个自定义的MyBatis Generator插件,用于扩展Mapper和XML文件,增加了批量插入和选择性批量插入的方法。插件通过配置属性指定了生成文件的目标位置和包名,并在生成的Mapper接口和XML映射文件中添加了新的批量操作方法。同时,展示了如何在Java代码中实现这些自定义方法。
摘要由CSDN通过智能技术生成
<?xml version="1.0" encoding="UTF-8"?>
<!--

       Copyright 2006-2022 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置参考 http://mybatis.org/generator/configreference/xmlconfig.html -->
<generatorConfiguration>
    <context id="testTables" targetRuntime="MyBatis3">

        <property name="javaFileEncoding" value="UTF-8"/>
        
        <!-- 自定义扩展mapper和xml -->
        <plugin type="com.ctl.MyExtendPlugin">
            <property name="targetXMLProject" value="/home/gitee/mybatis-generator-core/src/main/resources"/>
            <property name="targetJavaProject" value="/home/gitee/mybatis-generator-core/src/main/java"/>
            <property name="targetXMLPackage" value="com.ctl.mapper"/>
            <property name="targetJavaPackage" value="com.ctl.mapper"/>
        </plugin>
      
        <commentGenerator type="org.mybatis.generator.internal.DefaultCommentGenerator">
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/> <!-- 去除自动注释 -->
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <!-- &amp;=&   &gt;=> &lt;=< -->
        <jdbcConnection
                driverClass="com.mysql.cj.jdbc.Driver"
                connectionURL="jdbc:mysql://10.11.185.31:3306/test?verifyServerCertificate=false&amp;useSSL=false"
                userId="root"
                password="root@123@CTL"/>

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.ctl.po" targetProject="/home/gitee/mybatis-generator-core/src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.ctl.mapper" targetProject="/home/gitee/mybatis-generator-core/src/main/resources">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.ctl.mapper" targetProject="/home/gitee/mybatis-generator-core/src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 指定数据库表 -->
        <!--
            <table tableName="goods_info" domainObjectName="DispatchWayList" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
       -->
        <table tableName="tb_test"></table>

    </context>
</generatorConfiguration>
package com.ctl;

/*
 * 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.
 */


import org.mybatis.generator.api.*;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.*;
import org.mybatis.generator.codegen.XmlConstants;
import org.mybatis.generator.codegen.mybatis3.ListUtilities;
import org.mybatis.generator.codegen.mybatis3.MyBatis3FormattingUtilities;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.elements.InsertElementGenerator;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.internal.util.StringUtility;
import org.mybatis.generator.plugins.MapperConfigPlugin;

import java.util.*;

import static com.ctl.utils.PluginUtils.primaryKeyType;
import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;

/**
 * <p>Title: run</p>
 * <p>Description: 自定义扩展mapper和xml插件</p>
 * <p>Copyright: Copyright (c) 2022</p>
 * <p>Company: https://gitee.com/ctllin</p>
 *
 * @author ctl
 * @version 1.0
 * @date 2022-04-01 10:09
 */
public class MyExtendPlugin extends PluginAdapter {

    public static final String METHOD_BATCH_INSERT = "batchInsertExtend";  // 方法名
    public static final String METHOD_BATCH_INSERT_SELECTIVE = "batchInsertSelectiveExtend";  // 方法名
    public static final String EXTEND = "Extend";
    private String targetXMLProject = null;
    private String targetJavaProject = null;
    private String targetXMLPackage = null;
    private String targetJavaPackage = null;


    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public void setProperties(Properties properties) {
        super.setProperties(properties);
        targetXMLProject = properties.getProperty("targetXMLProject");
        targetJavaProject = properties.getProperty("targetJavaProject");
        targetXMLPackage = properties.getProperty("targetXMLPackage");
        targetJavaPackage = properties.getProperty("targetJavaPackage");
    }

    @Override
    public List<GeneratedXmlFile> contextGenerateAdditionalXmlFiles(IntrospectedTable introspectedTable) {
        Document document = new Document(
                XmlConstants.MYBATIS3_MAPPER_PUBLIC_ID,
                XmlConstants.MYBATIS3_MAPPER_SYSTEM_ID);
        //com.ctl.mapper.TbTestMapper
        String mapperFullName = introspectedTable.getMyBatis3JavaMapperType();
        XmlElement root = new XmlElement("mapper"); //$NON-NLS-1$
        root.addAttribute(new Attribute("namespace", mapperFullName + EXTEND));
        document.setRootElement(root);

        sqlMapDocumentGenerated(document,introspectedTable);

        //home/gitee/mybatis-generator-core/src/main/resources/com/ctl/mapper/TbTestMapperExtend.xml
        GeneratedXmlFile gxf = new GeneratedXmlFile(document, properties
                .getProperty("fileName", introspectedTable.getMyBatis3XmlMapperFileName().split("\\.")[0] + EXTEND + ".xml"),
                targetXMLPackage, //$NON-NLS-1$
                targetXMLProject, //$NON-NLS-1$
                false, context.getXmlFormatter());

        List<GeneratedXmlFile> answer = new ArrayList<>(1);
        answer.add(gxf);
        return answer;
    }


    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
        // 1. batchInsert
        XmlElement batchInsertEle = new XmlElement("insert");
        batchInsertEle.addAttribute(new Attribute("id", METHOD_BATCH_INSERT));
        // 参数类型
        batchInsertEle.addAttribute(new Attribute("parameterType", "map"));
        batchInsertEle.addElement(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime()));
        List<IntrospectedColumn> allColumns = introspectedTable.getAllColumns();
        StringBuffer buffer = new StringBuffer();
        buffer.append("(");
        for (int i = 0; i < allColumns.size(); i++) {
            IntrospectedColumn introspectedColumn = allColumns.get(i);
            if (i != allColumns.size() - 1) {
                buffer.append(introspectedColumn.getActualColumnName()).append(",");
            } else {
                buffer.append(introspectedColumn.getActualColumnName());
            }
        }
        buffer.append(")");

        batchInsertEle.addElement(new TextElement(buffer.toString()));
        StringBuilder valuesClause = new StringBuilder();
        valuesClause.append("("); //$NON-NLS-1$
        List<IntrospectedColumn> columns = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
        for (int i = 0; i < columns.size(); i++) {
            IntrospectedColumn introspectedColumn = columns.get(i);
            valuesClause.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn,"item."));
            if (i + 1 < columns.size()) {
                valuesClause.append(", "); //$NON-NLS-1$
            }
        }

        valuesClause.append(')');
        // 添加foreach节点
        XmlElement foreachElement = new XmlElement("foreach");
        foreachElement.addAttribute(new Attribute("collection", "list"));
        foreachElement.addAttribute(new Attribute("item", "item"));
        foreachElement.addAttribute(new Attribute("separator", ","));
        foreachElement.addElement(new TextElement(valuesClause.toString()));
        // values 构建
        batchInsertEle.addElement(new TextElement("values"));
        batchInsertEle.addElement(foreachElement);
        document.getRootElement().addElement(batchInsertEle);

        // 2. batchInsertSelective
        XmlElement batchInsertSelectiveEle = new XmlElement("insert");
        batchInsertSelectiveEle.addAttribute(new Attribute("id", METHOD_BATCH_INSERT_SELECTIVE));
        // 参数类型
        batchInsertSelectiveEle.addAttribute(new Attribute("parameterType", "map"));
        batchInsertSelectiveEle.getElements().addAll(this.generateSelectiveEnhancedEles(introspectedTable));
        document.getRootElement().addElement(batchInsertSelectiveEle);
        return true;
    }

    /**
     * 生成insert selective 增强的插入语句
     *
     * @param introspectedTable
     * @return
     */
    private List<VisitableElement> generateSelectiveEnhancedEles(IntrospectedTable introspectedTable) {
        List<VisitableElement> eles = new ArrayList<>();
        eles.add(new TextElement("insert into " + introspectedTable.getFullyQualifiedTableNameAtRuntime() + " ("));
        XmlElement foreachInsertColumns = new XmlElement("foreach");
        foreachInsertColumns.addAttribute(new Attribute("collection", "selective"));
        foreachInsertColumns.addAttribute(new Attribute("item", "column"));
        foreachInsertColumns.addAttribute(new Attribute("separator", ","));
        foreachInsertColumns.addElement(new TextElement("${column.column}"));
        eles.add(foreachInsertColumns);
        eles.add(new TextElement(")"));
        // values
        eles.add(new TextElement("values"));
        // foreach values
        XmlElement foreachValues = new XmlElement("foreach");
        foreachValues.addAttribute(new Attribute("collection", "list"));
        foreachValues.addAttribute(new Attribute("item", "item"));
        foreachValues.addAttribute(new Attribute("separator", ","));
        foreachValues.addElement(new TextElement("("));
        // foreach 所有插入的列,比较是否存在
        XmlElement foreachInsertColumnsCheck = new XmlElement("foreach");
        foreachInsertColumnsCheck.addAttribute(new Attribute("collection", "selective"));
        foreachInsertColumnsCheck.addAttribute(new Attribute("item", "column"));
        foreachInsertColumnsCheck.addAttribute(new Attribute("separator", ","));

        // 所有表字段
        List<IntrospectedColumn> columns = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
        List<IntrospectedColumn> columns1 = ListUtilities.removeIdentityAndGeneratedAlwaysColumns(introspectedTable.getAllColumns());
        for (int i = 0; i < columns1.size(); i++) {
            IntrospectedColumn introspectedColumn = columns.get(i);
            XmlElement check = new XmlElement("if");
            check.addAttribute(new Attribute("test", "'" + introspectedColumn.getActualColumnName() + "'.toString() == column.column"));
            check.addElement(new TextElement(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, "item.")));
            foreachInsertColumnsCheck.addElement(check);
        }
        foreachValues.addElement(foreachInsertColumnsCheck);
        foreachValues.addElement(new TextElement(")"));
        eles.add(foreachValues);
        return eles;
    }

    @Override
    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
        String superType = introspectedTable.getMyBatis3JavaMapperType();
        String extendMapperName = superType + "Extend";
        if (Objects.nonNull(targetJavaPackage) && Objects.nonNull(targetJavaProject)) {
            List<GeneratedJavaFile> files = new ArrayList<>();
            //Get entity class name
            String recordType = introspectedTable.getBaseRecordType();
            String[] entityPackage = recordType.split("\\.");
            String className = entityPackage[entityPackage.length - 1];
            //Create interface
//            String servicePackage = targetPackage + "." + className + "Service";
            FullyQualifiedJavaType service = new FullyQualifiedJavaType(extendMapperName);
            Interface interfaze = new Interface(service);
            interfaze.setVisibility(JavaVisibility.PUBLIC);


            if (Objects.nonNull(extendMapperName)) {
                //Import package
                interfaze.addImportedType(new FullyQualifiedJavaType(extendMapperName));
                //Interface name
                String[] basicServicePackage = extendMapperName.split("\\.");
                FullyQualifiedJavaType interfacePackage = new FullyQualifiedJavaType(superType);
                //接口添加泛型格式BaseService<实体,主键类型>
//                serviceInterface.addImportedType(new FullyQualifiedJavaType(recordType));
//                interfacePackage.addTypeArgument(new FullyQualifiedJavaType(recordType));
//                Optional<FullyQualifiedJavaType> optional = primaryKeyType(introspectedTable);
//                if (optional.isPresent()) {
//                    FullyQualifiedJavaType javaType = optional.get();
//                    if (javaType.isExplicitlyImported()) {
//                        serviceInterface.addImportedType(javaType);
//                    }
//                    interfacePackage.addTypeArgument(javaType);
//                }
                interfaze.addSuperInterface(interfacePackage);
                interfaze.addImportedType(new FullyQualifiedJavaType("java.util.List"));
                interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Param"));
                interfaze.addImportedType(new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()));//po 例如 com.ctl.po.TbTest

                GeneratedJavaFile javaFile = new GeneratedJavaFile(interfaze, targetJavaProject,
                        context.getProperty(PropertyRegistry.CONTEXT_JAVA_FILE_ENCODING),
                        context.getJavaFormatter());
                files.add(javaFile);

                // 1. batchInsert
                FullyQualifiedJavaType listType = FullyQualifiedJavaType.getNewListInstance();
                listType.addTypeArgument(introspectedTable.getRules().calculateAllFieldsClass());
                Method batchInsertSelectiveMethod = new Method(METHOD_BATCH_INSERT_SELECTIVE);
                batchInsertSelectiveMethod.setReturnType(FullyQualifiedJavaType.getIntInstance());
                batchInsertSelectiveMethod.setVisibility(JavaVisibility.DEFAULT);
                batchInsertSelectiveMethod.addParameter(new Parameter(listType, "list", "@Param(\"list\")"));
                FullyQualifiedJavaType selectiveType = new FullyQualifiedJavaType(introspectedTable.getRules().calculateAllFieldsClass().getShortName() + "." + MyColumnPlugin.ENUM_NAME);
                batchInsertSelectiveMethod.addParameter(new Parameter(selectiveType, "selective", "@Param(\"selective\")", true));
                batchInsertSelectiveMethod.setAbstract(true);

                Method batchInsertMethod = new Method(METHOD_BATCH_INSERT);
                batchInsertMethod.setReturnType(FullyQualifiedJavaType.getIntInstance());
                batchInsertMethod.setVisibility(JavaVisibility.DEFAULT);
                batchInsertMethod.addParameter(new Parameter(listType, "list", "@Param(\"list\")"));
                batchInsertMethod.setAbstract(true);

                interfaze.addMethod(batchInsertSelectiveMethod);
                interfaze.addMethod(batchInsertMethod);


            }

            return files;
        }
        return Collections.emptyList();
    }

}

生成的自定义Mapper.java

package com.ctl.mapper;

import com.ctl.po.TbTest;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface TbTestMapperExtend extends TbTestMapper {
    int batchInsertSelectiveExtend(@Param("list") List<TbTest> list, @Param("selective") TbTest.Columns ... selective);

    int batchInsertExtend(@Param("list") List<TbTest> list);
}

 生成的自定义Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ctl.mapper.TbTestMapperExtend">
  <insert id="batchInsertExtend" parameterType="map">
    insert into tb_test
    (id,source,var,default_address,content)
    values
    <foreach collection="list" item="item" separator=",">
      (#{item.id,jdbcType=BIGINT}, #{item.source,jdbcType=INTEGER}, #{item.var,jdbcType=CHAR}, #{item.defaultAddress,jdbcType=VARCHAR}, #{item.content,jdbcType=LONGVARCHAR})
    </foreach>
  </insert>
  <insert id="batchInsertSelectiveExtend" parameterType="map">
    insert into tb_test (
    <foreach collection="selective" item="column" separator=",">
      ${column.column}
    </foreach>
    )
    values
    <foreach collection="list" item="item" separator=",">
      (
      <foreach collection="selective" item="column" separator=",">
        <if test="'id'.toString() == column.column">
          #{item.id,jdbcType=BIGINT}
        </if>
        <if test="'source'.toString() == column.column">
          #{item.source,jdbcType=INTEGER}
        </if>
        <if test="'var'.toString() == column.column">
          #{item.var,jdbcType=CHAR}
        </if>
        <if test="'default_address'.toString() == column.column">
          #{item.defaultAddress,jdbcType=VARCHAR}
        </if>
        <if test="'content'.toString() == column.column">
          #{item.content,jdbcType=LONGVARCHAR}
        </if>
      </foreach>
      )
    </foreach>
  </insert>
</mapper>

代码示例ctllin/mybatis-generator-core

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值