MybatisPlus报错error: entityList must not be empty

这篇博客讲述了作者在实现数据处理定时任务时遇到的问题,即在使用saveOrUpdateBatch方法保存空集合时触发异常。作者强调在开发中应当对集合为空的情况进行判断,避免批量操作时因空集合引发的错误。解决方案是在保存前增加集合非空判断,以增强代码健壮性。在处理批量数据时,需要注意各种边界条件和异常情况,确保程序的稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

昨天写了几个数据处理的定时任务,晚上放到服务器上跑竟然报错了,看到群里的消息连夜爬起来改bug

集合为空保存不了,saveBatch方法保存空集合也没出过问题,这个saveOrUpdateBatch方法里面有对集合的判断,如果集合为空直接报错。开发的时候就要对集合进行判断,集合为空不执行批量保存修改这个方法。

public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) {
        Assert.notEmpty(entityList, "error: entityList must not be empty");
        Class<?> cls = currentModelClass();
        TableInfo tableInfo = TableInfoHelper.getTableInfo(cls);
        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!");
        try (SqlSession batchSqlSession = sqlSessionBatch()) {
            int i = 0;
            for (T entity : entityList) {
                Object idVal = ReflectionKit.getMethodValue(cls, entity, keyProperty);
                if (StringUtils.checkValNull(idVal) || Objects.isNull(getById((Serializable) idVal))) {
                    batchSqlSession.insert(sqlStatement(SqlMethod.INSERT_ONE), entity);
                } else {
                    MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
                    param.put(Constants.ENTITY, entity);
                    batchSqlSession.update(sqlStatement(SqlMethod.UPDATE_BY_ID), param);
                }
                // 不知道以后会不会有人说更新失败了还要执行插入 😂😂😂
                if (i >= 1 && i % batchSize == 0) {
                    batchSqlSession.flushStatements();
                }
                i++;
            }
            batchSqlSession.flushStatements();
        }
        return true;
    }

解决方法在保存之前加个判断,如果集合为空直接结束。在批量处理数据的方法里面要注意各种极端情况,注意对空集合空数据的判断,以免出现各种错误。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值