iis服务器助手广告广告
返回顶部
首页 > 资讯 > 数据库 >Mybatis-plus批量操作
  • 837
分享到

Mybatis-plus批量操作

mybatisjavamysql 2023-09-01 15:09:26 837人浏览 独家记忆
摘要

前言         使用mybatis-plus可以很方便的实现批量新增和批量修改,不仅比自己写foreach遍历方便很多,而且性能也更加优秀。但是Mybatis-plus官方提供的批量修改和批量新增都是根据id来修改的,有时候我们需求其

前言

        使用mybatis-plus可以很方便的实现批量新增和批量修改,不仅比自己写foreach遍历方便很多,而且性能也更加优秀。但是Mybatis-plus官方提供的批量修改和批量新增都是根据id来修改的,有时候我们需求其他字段,所以就需要我们自己修改一下。

一、批量修改

        在Mybatis-plus的IService接口中有updateBatchById方法,我们常用以下方法根据id批量修改数据。

    @Transactional(rollbackFor = Exception.class)    default boolean updateBatchById(Collection entityList) {        return updateBatchById(entityList, DEFAULT_BATCH_SIZE);    }    @Transactional(rollbackFor = Exception.class)    @Override    public boolean updateBatchById(Collection entityList, int batchSize) {        String sqlStatement = getSqlStatement(SqlMethod.UPDATE_BY_ID);        return executeBatch(entityList, batchSize, (sqlSession, entity) -> {            MapperMethod.ParamMap param = new MapperMethod.ParamMap<>();            param.put(Constants.ENTITY, entity);            sqlSession.update(sqlStatement, param);        });    }

但是当我们想根据其他字段批量修改数据时,该方法就无能为力了。所以我们就可以根据第二个updateBatchById方法在自己的service类里面写一个新的批量新增方法。

    public boolean updateBatchByColumn(Collection entityList, String idCard) {        String sqlStatement = getSqlStatement(SqlMethod.UPDATE);        return executeBatch(entityList, (sqlSession, entity) -> {            LambdaUpdateWrapper updateWrapper = Wrappers.lambdaUpdate()                    .eq(SysUser::getIdCard, idCard);            Map param = CollectionUtils.newHashMapWithExpectedSize(2);            param.put(Constants.ENTITY, entity);            param.put(Constants.WRAPPER, updateWrapper);            sqlSession.update(sqlStatement, param);        });    }

注意sqlStatement是使用的SqlMethod.UPDATE,SysUser对象是举例,使用的是若依的用户数据。

二、批量新增或修改

        在Mybatis-plus的ServiceImpl 类中有一个saveOrUpdateBatch 方法用于批量新增或修改,通过CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_BY_ID), entity))根据id查询数据是否已存在,不存在新增,存在则修改,源码如下:

    @Transactional(rollbackFor = Exception.class)    @Override    public boolean saveOrUpdateBatch(Collection entityList, int batchSize) {        TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);        Assert.notNull(tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");        String keyProperty = tableInfo.getKeyProperty();        Assert.notEmpty(keyProperty, "error: can not execute. because can not find column for id from entity!");        return SqlHelper.saveOrUpdateBatch(this.entityClass, this.mapperClass, this.log, entityList, batchSize, (sqlSession, entity) -> {            Object idVal = tableInfo.getPropertyValue(entity, keyProperty);            return StringUtils.checkValNull(idVal)                || CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_BY_ID), entity));        }, (sqlSession, entity) -> {            MapperMethod.ParamMap param = new MapperMethod.ParamMap<>();            param.put(Constants.ENTITY, entity);            sqlSession.update(getSqlStatement(SqlMethod.UPDATE_BY_ID), param);        });    }

最终调用的是SqlHelper.saveOrUpdateBatch方法,该方法第六个参数是BiPredicate,这就是用于判断数据库中数据是否存在的关键,所以我们需要修改这个函数式接口,修改为根据其他条件查询数据库。该方法的第七个参数是BiConsumer,该函数式接口用于修改数据,如果不想根据id修改数据,可以参考第一部门进行修改。

    @Transactional(rollbackFor = Exception.class)    public boolean saveOrUpdateBatchByColumn(Collection entityList, String idCard) {        return SqlHelper.saveOrUpdateBatch(this.entityClass, this.mapperClass, super.log, entityList, DEFAULT_BATCH_SIZE, (sqlSession, entity) -> {            LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery()                    .eq(SysUser::getIdCard, idCard);            Map map = CollectionUtils.newHashMapWithExpectedSize(1);            map.put(Constants.WRAPPER, queryWrapper);            return CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_LIST), map));        }, (sqlSession, entity) -> {            Map param = CollectionUtils.newHashMapWithExpectedSize(2);            param.put(Constants.ENTITY, entity);            sqlSession.update(getSqlStatement(SqlMethod.UPDATE_BY_ID), param);        });    }

三、不使用Mybatis-plus进行批量操作

        有时候项目里没有引用Mybatis-plus,但是也想进行批量操作,数据量大了后foreach循环会影响性能。所以可以参考Mybatis-plus的批量操作,编写在mybatis环境下的批量操作,代码如下:

@Componentpublic class MybatisBatchUtils {    private static final int BATCH_SIZE = 1000;    @Autowired    private SqlSessionFactory sqlSessionFactory;    public  boolean batchUpdateOrInsert(List data, Class mapperClass, BiFunction function) {        int i = 1;        SqlSession batchSqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);        try {            U mapper = batchSqlSession.getMapper(mapperClass);            int size = data.size();            for (T element : data) {                function.apply(element, mapper);                if ((i % BATCH_SIZE == 0) || i == size) {                    batchSqlSession.flushStatements();                }                i++;            }            // 非事务环境下强制commit,事务情况下该commit相当于无效            batchSqlSession.commit(!TransactionSynchronizationManager.isSynchronizationActive());            return true;        } catch (Exception e) {            batchSqlSession.rollback();            throw new RuntimeException(e);        } finally {            batchSqlSession.close();        }    }}

写在最后的话

        Mybatis-plus真好用,少写好多代码。有些不太适用的方法,也可以很简单在官方的基础上进行扩展。

来源地址:https://blog.csdn.net/WayneLee0809/article/details/126424482

您可能感兴趣的文档:

--结束END--

本文标题: Mybatis-plus批量操作

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

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

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

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

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

  • 微信公众号

  • 商务合作