广告
返回顶部
首页 > 资讯 > 后端开发 > Python >mybatis-plus扩展批量新增的实现
  • 185
分享到

mybatis-plus扩展批量新增的实现

mybatis-plus批量新增mybatis-plus新增 2023-01-09 15:01:30 185人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录前言一、MP如何扩展批量新增方法?二、实现步骤1.扩展批插类2.编写sql注入器3.spring容器中实例化sql注入器总结前言 最近发现公司的微服务项目中没有统一的批量新增方法

前言

最近发现公司的微服务项目中没有统一的批量新增方法,公司用的是MP插件,遇到批量新增都是单独去去编写xml实现,费时费力,而MP自带的批插方法只是实现了分批条sql,跟真正意义上一条sql实现批插还是有很大的性能差异,所以决定实现一个统一的批插方法。

一、MP如何扩展批量新增方法?

MP给我们预留了一个可以真正实现批插的插件InsertBatchSomeColumn,但是只是针对Mysql数据库的,我们可以参照它稍加改造扩展一个针对oracle或者其他数据库的批插插件类,然后通过sql注入器的方式注入并初始化,就可以实现真正的批插了。

二、实现步骤

1.扩展批插类

代码如下(示例):

public class InsertBatchSomeColumnOracle extends AbstractMethod {

    
    @Setter
    @Accessors(chain = true)
    private Predicate<TableFieldInfo> predicate;

    @SuppressWarnings("Duplicates")
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        KeyGenerator keyGenerator = new NoKeyGenerator();
        SqlMethod sqlMethod = SqlMethod.INSERT_ALL;
        List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        String insertSqlColumn = tableInfo.geTKEyInsertSqlColumn(false) +
                this.filterTableFieldInfo(fieldList, predicate, TableFieldInfo::getInsertSqlColumn, EMPTY);
        String tableName = tableInfo.getTableName();
        String columnScript = LEFT_BRACKET + insertSqlColumn.substring(0, insertSqlColumn.length() - 1) + RIGHT_BRACKET;
        String insertSqlProperty = tableInfo.getKeyInsertSqlProperty(ENTITY_DOT, false) +
                this.filterTableFieldInfo(fieldList, predicate, i -> i.getInsertSqlProperty(ENTITY_DOT), EMPTY);
        insertSqlProperty = " into " + tableName + columnScript + " values " + LEFT_BRACKET + insertSqlProperty.substring(0, insertSqlProperty.length() - 1) + RIGHT_BRACKET;
        String batchScript = SqlScriptUtils.convertForeach(insertSqlProperty, "list", null, ENTITY, EMPTY);
        String keyProperty = null;
        String keyColumn = null;
        // 表包含主键处理逻辑,如果不包含主键当普通字段处理
        if (tableInfo.havePK()) {
            if (tableInfo.getIdType() == IdType.AUTO) {
                
                keyGenerator = new Jdbc3KeyGenerator();
                keyProperty = tableInfo.getKeyProperty();
                keyColumn = tableInfo.getKeyColumn();
            } else {
                if (null != tableInfo.getKeySequence()) {
                    keyGenerator = TableInfoHelper.genKeyGenerator(getMethod(), tableInfo, builderAssistant);
                    keyProperty = tableInfo.getKeyProperty();
                    keyColumn = tableInfo.getKeyColumn();
                }
            }
        }
        String sql = String.fORMat(sqlMethod.getSql(), batchScript);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addInsertMappedStatement(mapperClass, modelClass, getMethod(), sqlSource, keyGenerator, keyProperty, keyColumn);
    }

    public String getMethod() {
        // 自定义 mapper 方法名
        return "insertBatchSomeColumnOracle";
    }
}

2.编写sql注入器

代码如下(示例):

public class MpSqlInjector extends DefaultSqlInjector {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
        // 防止父类的方法不可使用
        List<AbstractMethod> methodList = super.getMethodList(mapperClass);
        // 添加批量插入的方法
        methodList.add(new InsertBatchSomeColumn());
        methodList.add(new InsertBatchSomeColumnOracle());
        return methodList;
    }
}

3.spring容器中实例化sql注入器

代码如下(示例):

@Bean
public MpSqlInjector mpSqlInjector() {
    return new MpSqlInjector();
}

4.业务代码实现

代码如下(示例):

public interface MyBaseMapper<T> extends BaseMapper<T> {

    
    int insertBatchSomeColumn(Collection<T> entityList);

    
    int insertBatchSomeColumnOracle(Collection<T> entityList);
}



    public void saveBatch(Collection<T> entityList) {
        if (DEFAULT_MUST_SAVE_BATCH) {
            ServiceAssert.isTrue(CollectionUtil.isNotEmpty(entityList), "批量插入传入空集合, 插入失败");
        }
        if (CollectionUtil.isEmpty(entityList)) {
            return;
        }
        int res;
        if (DATABASE_TYPE_ORACLE.equalsIgnoreCase(dbType)) {
            res = getBaseMapper().insertBatchSomeColumnOracle(entityList);
        } else {
            res = getBaseMapper().insertBatchSomeColumn(entityList);
        }
        ServiceAssert.isTrue(res == entityList.size(), "插入失败,请联系管理员");
    }
    
    public void saveBatch(Collection<T> entityList, int batchSize) {
        if (DEFAULT_MUST_SAVE_BATCH) {
            ServiceAssert.isTrue(CollectionUtil.isNotEmpty(entityList), "批量插入传入空集合, 插入失败");
        }
        if (CollectionUtil.isEmpty(entityList)) {
            return;
        }
        int size = entityList.size();
        int idxLimit = Math.min(batchSize, size);
        int i = 1;
        //保存单批提交的数据集合
        List<T> batchList = new ArrayList<>();
        for(Iterator<T> it = entityList.iterator(); it.hasNext(); ++i) {
            T element = it.next();
            batchList.add(element);
            int res;
            if (i == idxLimit) {
                if (DATABASE_TYPE_ORACLE.equalsIgnoreCase(dbType)) {
                    res = getBaseMapper().insertBatchSomeColumnOracle(batchList);
                } else {
                    res = getBaseMapper().insertBatchSomeColumn(batchList);
                }
                //每次提交后需要清空集合数据
                batchList.clear();
                idxLimit = Math.min(idxLimit + batchSize, size);
                ServiceAssert.isTrue(res == entityList.size(), "插入失败,请联系管理员");
            }
        }
    }

总结

遇到问题可以看看源码,说不定作者已经给你留好路了。

到此这篇关于mybatis-plus 扩展批量新增的实现的文章就介绍到这了,更多相关mybatis-plus 批量新增内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: mybatis-plus扩展批量新增的实现

本文链接: https://www.lsjlt.com/news/177192.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作