mybatis-plus如何根据任意字段saveOrUpdateBatch

 更新时间:2025年09月01日 08:57:54   作者:孤海岛主  
MyBatisPlus saveOrUpdateBatch默认按主键判断操作类型,若需按其他唯一字段(如agentId、period、type组合)判断,需在service层重写方法,通过predicate定义插入条件并结合consumer执行更新逻辑,适用于批量和单条数据操作场景

使用场景

mybatisplus Iservice接口下的saveOrUpdateBatch方法默认是根据主键来决定是要更新还是插入的,

如果要根据其他字段(必须是唯一约束,唯一约束字段可以是多个)更新的话,则需要在项目的service层重写该方法。

方法源码

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

从源码中可以看出实现saveOrUpdateBatch的主要方法就是SqlHelper.saveOrUpdateBatch

public static <E> boolean saveOrUpdateBatch(Class<?> entityClass, Class<?> mapper, Log log, Collection<E> list, int batchSize, BiPredicate<SqlSession, E> predicate, BiConsumer<SqlSession, E> consumer) {
        String sqlStatement = getSqlStatement(mapper, SqlMethod.INSERT_ONE);
        return executeBatch(entityClass, log, list, batchSize, (sqlSession, entity) -> {
            if (predicate.test(sqlSession, entity)) {
                sqlSession.insert(sqlStatement, entity);
            } else {
                consumer.accept(sqlSession, entity);
            }

        });
    }

该方法的最后两个参数predicate,consumer

predicate 这个函数是用于判断是否要进行插入操作 true插入,false:则通过consumer 函数执行更新

方法改造

注意:写在项目操作对应表的service层

首先在service层定义接口

boolean saveOrUpdateBatchByAgentIdAndPeriodAndType(List<Entity> list);

类为数据库表对应的实体类,agentId,period,type,这个三个字段为表的唯一约束,即当表中存在这三个字段组合对应的记录时则进行更新操作,不存在则进行插入操作

service层接口实现

@Transactional(rollbackFor = Exception.class)
    @DS("XXXX")//如果为多数据源,这里要指明具体操作的数据源名称
    public boolean saveOrUpdateBatchByAgentIdAndPeriodAndType(List<Entity> list) {

        return SqlHelper.saveOrUpdateBatch(entityClass, this.mapperClass, super.log, list, DEFAULT_BATCH_SIZE, (sqlSession, entity) -> {//这里主要是查询唯一约束对应的记录是否存在
            LambdaQueryWrapper<Entity> queryWrapper = Wrappers.<Entity>lambdaQuery()
                    .eq(Entity::getAgentId, entity.getAgentId()).eq(Entity::getPeriod,entity.getPeriod())
                    .eq(Entity::getType,entity.getType());
            Map<String, Object> map = CollectionUtils.newHashMapWithExpectedSize(1);
            map.put(Constants.WRAPPER, queryWrapper);
            return CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_LIST), map));
        }, (sqlSession, entity) -> {
            LambdaUpdateWrapper<Entity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(Entity::getAgentId, entity.getAgentId()).eq(Entity::getPeriod,entity.getPeriod())
                    .eq(Entity::getType,entity.getType());
            Map<String, Object> param = CollectionUtils.newHashMapWithExpectedSize(2);
            param.put(Constants.ENTITY, entity);
            param.put(Constants.WRAPPER, lambdaUpdateWrapper);
            sqlSession.update(getSqlStatement(SqlMethod.UPDATE), param);
        });
    }

非批量的saveOrUpdate也可以按照这种方式进行改造

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • springboot的war和jar包的使用详解

    springboot的war和jar包的使用详解

    这篇文章主要介绍了springboot的war和jar包的使用详解,非常不错,具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2018-11-11
  • El表达式使用问题javax.el.ELException:Failed to parse the expression的解决方式

    El表达式使用问题javax.el.ELException:Failed to parse the expression

    今天小编就为大家分享一篇关于Jsp El表达式使用问题javax.el.ELException:Failed to parse the expression的解决方式,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-12-12
  • java 面向对象代码块及不同位置对属性赋值的执行顺序

    java 面向对象代码块及不同位置对属性赋值的执行顺序

    这篇文章主要介绍了java面向对象代码块及不同位置对属性赋值的执行顺序,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • 使用注解进行Spring开发的全过程

    使用注解进行Spring开发的全过程

    使用注解(Annotation)是一种在代码级别进行说明和标记的技术,它从JDK 5.0开始引入,并在现代Java开发中得到了广泛应用,本文将详细介绍Spring框架中常用的注解及示例,帮助开发者快速掌握Spring注解开发的要点和技巧,需要的朋友可以参考下
    2023-11-11
  • RocketMQTemplate 注入失败的解决

    RocketMQTemplate 注入失败的解决

    这篇文章主要介绍了RocketMQTemplate 注入失败的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Java中比较器Comparable和Comparator超详细解析

    Java中比较器Comparable和Comparator超详细解析

    Java中在进行数据排序时,Comparable和Comparator必不可少会遇得到,这篇文章主要给大家介绍了关于Java中比较器Comparable和Comparator的相关资料,需要的朋友可以参考下
    2025-06-06
  • 浅析JVM逃逸的原理及分析

    浅析JVM逃逸的原理及分析

    在本篇文章里我们给大家分享了JVM逃逸的原理及分析的相关知识点内容,需要的读者们可以学习下。
    2018-10-10
  • Java Dump概述及应用场景

    Java Dump概述及应用场景

    Java中的Dump是指在运行时导出程序的状态数据,用于调试、分析和排查问题,Dump文件常用于定位性能瓶颈、内存泄漏、线程死锁等问题,这篇文章给大家介绍Java Dump概述及应用场景,感兴趣的朋友跟随小编一起看看吧
    2026-01-01
  • SpringBoot应用刚启动时服务报大量超时的问题及解决

    SpringBoot应用刚启动时服务报大量超时的问题及解决

    在Java项目上线过程中,经常遇到的超时问题主要是由于JVM的JIT编译导致,JIT(Just-In-Time)编译是Java虚拟机的一项技术,用于提高Java应用的性能,它通过将热点代码(频繁执行的部分)转换成本地机器码来优化执行效率
    2024-11-11
  • java在cmd运行"-d"和"-cp"参数解读

    java在cmd运行"-d"和"-cp"参数解读

    这篇文章主要介绍了java在cmd运行"-d"和"-cp"参数用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08

最新评论