MybatisGenerator插件开发四【批量插入】

栏目: 数据库 · 发布时间: 6年前

内容简介:批量插入和分页查询一样,在项目中基本也是不可少的。这里我们要给Mapper添加两个方法:下面直接上代码。上述代码在Mapper接口和SqlMap文件中添加了

批量插入和分页查询一样,在项目中基本也是不可少的。这里我们要给Mapper添加两个方法: batchInsertbatchInsertSelective ,区别是前者全字段插入,后者只插入给定的字段。原来的单条 insertSelective 是通过对象的值是不是Null来实现的,我们也可以取插入记录的第0条来实现 batchInsertSelective 。但是,始终感觉有点不对,所以采取了另一种方式,显式地传递要插入地字段来实现。这里就会用到了上一章节写入到Model中的表字段枚举了。

下面直接上代码。

修改Mapper接口和SqlMap文件

public class BatchInsertPluginextends PluginAdapter{


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

    /**
     * 修改Mapper类
     */
    @Override
    public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable){
        addBatchInsertMethod(interfaze, introspectedTable);
        return true;
    }

    private void addBatchInsertMethod(Interface interfaze, IntrospectedTable introspectedTable){
        // 设置需要import的类
        Set<FullyQualifiedJavaType> importedTypes = new TreeSet<>();
        importedTypes.add(FullyQualifiedJavaType.getNewListInstance());
        importedTypes.add(new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()));

        FullyQualifiedJavaType ibsreturnType = FullyQualifiedJavaType.getIntInstance();

        Method batchInsertMethod = new Method();
        // 1.设置方法可见性
        batchInsertMethod.setVisibility(JavaVisibility.PUBLIC);
        // 2.设置返回值类型 int类型
        batchInsertMethod.setReturnType(ibsreturnType);
        // 3.设置方法名
        batchInsertMethod.setName("batchInsert");
        // 4.设置参数列表
        FullyQualifiedJavaType paramType = FullyQualifiedJavaType.getNewListInstance();
        FullyQualifiedJavaType paramListType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        paramType.addTypeArgument(paramListType);
        batchInsertMethod.addParameter(new Parameter(paramType, "records"));
        interfaze.addImportedTypes(importedTypes);
        interfaze.addMethod(batchInsertMethod);

        Method batchInsertSelectiveMethod = new Method();
        // 1.设置方法可见性
        batchInsertSelectiveMethod.setVisibility(JavaVisibility.PUBLIC);
        // 2.设置返回值类型 int类型
        batchInsertSelectiveMethod.setReturnType(ibsreturnType);
        // 3.设置方法名
        batchInsertSelectiveMethod.setName("batchInsertSelective");
        // 4.设置参数列表
        FullyQualifiedJavaType paramTypeSelective = FullyQualifiedJavaType.getNewListInstance();
        FullyQualifiedJavaType paramListTypeSelective = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        paramTypeSelective.addTypeArgument(paramListTypeSelective);
        batchInsertSelectiveMethod.addParameter(new Parameter(paramTypeSelective, "records", "@Param(\"records\")"));
        batchInsertSelectiveMethod.addParameter(new Parameter(FullyQualifiedJavaType.getStringInstance(), "columns", "@Param(\"columns\")", true));
        interfaze.addImportedTypes(importedTypes);
        interfaze.addMethod(batchInsertSelectiveMethod);
    }


    /**
     * 修改Mapper.xml
     */
    @Override
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable){
        addBatchInsertXml(document, introspectedTable);
        addBatchInsertSelectiveXml(document, introspectedTable);
        return true;
    }

    private void addBatchInsertXml(Document document, IntrospectedTable introspectedTable){
        // <insert ...
        XmlElement insertBatchElement = new XmlElement("insert");
        insertBatchElement.addAttribute(new Attribute("id", "batchInsert"));
        insertBatchElement.addAttribute(new Attribute("parameterType", "java.util.List"));

        XmlElement valueTrimElement = new XmlElement("trim");
        valueTrimElement.addAttribute(new Attribute("prefix", " ("));
        valueTrimElement.addAttribute(new Attribute("suffix", ")"));
        valueTrimElement.addAttribute(new Attribute("suffixOverrides", ","));

        XmlElement columnTrimElement = new XmlElement("trim");
        columnTrimElement.addAttribute(new Attribute("prefix", "("));
        columnTrimElement.addAttribute(new Attribute("suffix", ")"));
        columnTrimElement.addAttribute(new Attribute("suffixOverrides", ","));
        List<IntrospectedColumn> columns = introspectedTable.getAllColumns();

        for (IntrospectedColumn introspectedColumn : columns) {
            String columnName = introspectedColumn.getActualColumnName();
            columnTrimElement.addElement(new TextElement(columnName+","));
            valueTrimElement.addElement(new TextElement("#{item." + introspectedColumn.getJavaProperty() + ",jdbcType=" + introspectedColumn.getJdbcTypeName() + "},"));
        }

        XmlElement foreachElement = new XmlElement("foreach");
        foreachElement.addAttribute(new Attribute("collection", "list"));
        foreachElement.addAttribute(new Attribute("index", "index"));
        foreachElement.addAttribute(new Attribute("item", "item"));
        foreachElement.addAttribute(new Attribute("separator", ","));
        insertBatchElement.addElement(new TextElement("insert into " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
        insertBatchElement.addElement(columnTrimElement);
        insertBatchElement.addElement(new TextElement(" values "));
        foreachElement.addElement(valueTrimElement);
        insertBatchElement.addElement(foreachElement);

        document.getRootElement().addElement(insertBatchElement);
    }

    private void addBatchInsertSelectiveXml(Document document, IntrospectedTable introspectedTable){
        // <insert ...
        XmlElement insertBatchElement = new XmlElement("insert");
        insertBatchElement.addAttribute(new Attribute("id", "batchInsertSelective"));
        insertBatchElement.addAttribute(new Attribute("parameterType", "map"));

        XmlElement foreachColumn = new XmlElement("foreach");
        foreachColumn.addAttribute(new Attribute("collection", "columns"));
        foreachColumn.addAttribute(new Attribute("index", "index"));
        foreachColumn.addAttribute(new Attribute("item", "item"));
        foreachColumn.addAttribute(new Attribute("separator", ","));
        foreachColumn.addAttribute(new Attribute("open", "("));
        foreachColumn.addAttribute(new Attribute("close", ")"));
        foreachColumn.addElement(new TextElement("${item}"));

        insertBatchElement.addElement(new TextElement("insert into " + introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime()));
        insertBatchElement.addElement(foreachColumn);
        insertBatchElement.addElement(new TextElement(" values "));


        XmlElement valueTrimElement = new XmlElement("trim");
        valueTrimElement.addAttribute(new Attribute("prefix", " ("));
        valueTrimElement.addAttribute(new Attribute("suffix", ")"));
        valueTrimElement.addAttribute(new Attribute("suffixOverrides", ","));

        XmlElement foreachColumnForValue = new XmlElement("foreach");
        foreachColumnForValue.addAttribute(new Attribute("collection", "columns"));
        foreachColumnForValue.addAttribute(new Attribute("index", "index"));
        foreachColumnForValue.addAttribute(new Attribute("item", "column"));

        List<IntrospectedColumn> columns = introspectedTable.getAllColumns();
        for (IntrospectedColumn introspectedColumn : columns) {
            String columnName = introspectedColumn.getActualColumnName();
            XmlElement check = new XmlElement("if");
            check.addAttribute(new Attribute("test", "'" + columnName + "' == column"));
            check.addElement(new TextElement("#{record." + introspectedColumn.getJavaProperty() + ",jdbcType=" + introspectedColumn.getJdbcTypeName() + "},"));
            foreachColumnForValue.addElement(check);
        }
        valueTrimElement.addElement(foreachColumnForValue);
        XmlElement foreachElement = new XmlElement("foreach");
        foreachElement.addAttribute(new Attribute("collection", "records"));
        foreachElement.addAttribute(new Attribute("index", "index"));
        foreachElement.addAttribute(new Attribute("item", "record"));
        foreachElement.addAttribute(new Attribute("separator", ","));
        foreachElement.addElement(valueTrimElement);

        insertBatchElement.addElement(foreachElement);
        document.getRootElement().addElement(insertBatchElement);
    }
}

上述代码在Mapper接口和SqlMap文件中添加了 batchInsertbatchInsertSelective 的支持。

查看生成文件

将插件添加到项目中,并且运行完MybatisGenerator,我们来查看下生成的相关文件:

public interface AdministratorMapper{
    ...
    int batchInsert(List<Administrator> records);

    int batchInsertSelective(@Param("records")List<Administrator> records, @Param("columns")String ... columns);
    ...
}
...
<insertid="batchInsert"parameterType="java.util.List">
    insert into administrator
    <trimprefix="("suffix=")"suffixOverrides=",">
      id,
      mobile,
      pwd,
      role,
      deleted,
      create_time,
      update_time,
    </trim>
     values 
    <foreachcollection="list"index="index"item="item"separator=",">
      <trimprefix=" ("suffix=")"suffixOverrides=",">
        #{item.id,jdbcType=BIGINT},
        #{item.mobile,jdbcType=VARCHAR},
        #{item.pwd,jdbcType=VARCHAR},
        #{item.role,jdbcType=TINYINT},
        #{item.deleted,jdbcType=INTEGER},
        #{item.createTime,jdbcType=BIGINT},
        #{item.updateTime,jdbcType=BIGINT},
      </trim>
    </foreach>
  </insert>
  <insertid="batchInsertSelective"parameterType="map">
    insert into administrator
    <foreachclose=")"collection="columns"index="index"item="item"open="("separator=",">
      ${item}
    </foreach>
     values 
    <foreachcollection="records"index="index"item="record"separator=",">
      <trimprefix=" ("suffix=")"suffixOverrides=",">
        <foreachcollection="columns"index="index"item="column">
          <iftest="'id' == column">
            #{record.id,jdbcType=BIGINT},
          </if>
          <iftest="'mobile' == column">
            #{record.mobile,jdbcType=VARCHAR},
          </if>
          <iftest="'pwd' == column">
            #{record.pwd,jdbcType=VARCHAR},
          </if>
          <iftest="'role' == column">
            #{record.role,jdbcType=TINYINT},
          </if>
          <iftest="'deleted' == column">
            #{record.deleted,jdbcType=INTEGER},
          </if>
          <iftest="'create_time' == column">
            #{record.createTime,jdbcType=BIGINT},
          </if>
          <iftest="'update_time' == column">
            #{record.updateTime,jdbcType=BIGINT},
          </if>
        </foreach>
      </trim>
    </foreach>
  </insert>
...

如何使用

使用方式如下:

administratorMapper.batchInsertSelective(
    list,
    Administrator.COLUMNS.ID.getColumn(),
    Administrator.COLUMNS.MOBILE.getColumn()
);

本章节就到这里了。


以上所述就是小编给大家介绍的《MybatisGenerator插件开发四【批量插入】》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

你不知道的JavaScript(中卷)

你不知道的JavaScript(中卷)

[美] Kyle Simpson / 单业、姜南 / 人民邮电出版社 / 2016-8 / 79.00元

JavaScript这门语言简单易用,很容易上手,但其语言机制复杂微妙,即使是经验丰富的JavaScript开发人员,如果没有认真学习的话也无法真正理解。本套书直面当前JavaScript开发人员不求甚解的大趋势,深入理解语言内部的机制,全面介绍了JavaScript中常被人误解和忽视的重要知识点。本书是其中卷,主要介绍了类型、语法、异步和性能。一起来看看 《你不知道的JavaScript(中卷)》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

MD5 加密
MD5 加密

MD5 加密工具