mybatis-plus icon indicating copy to clipboard operation
mybatis-plus copied to clipboard

saveOrUpdate 和 saveOrUpdateBatch 优化

Open weitangli opened this issue 2 years ago • 4 comments

当前使用版本(必填,否则不予处理)

3.5.1

该问题是如何引起的?(确定最新版也有问题再提!!!)

以saveOrUpdateBatch方法为例,在判断是执行新增还是修改的predicate中,会先判断idVal是否为空,然后再根据selectList判断数据是否存在,这里建议使用count来判断。

    com.baomidou.mybatisplus.extension.service.impl.ServiceImpl

    public boolean saveOrUpdateBatch(Collection<T> 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);
            // 此处判断 idVal 是否存在
            return StringUtils.checkValNull(idVal)
                // 此处根据 selectList 查询数据出来,判断是否为空
                || CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_BY_ID), entity));
        }, (sqlSession, entity) -> {
            MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
            param.put(Constants.ENTITY, entity);
            sqlSession.update(getSqlStatement(SqlMethod.UPDATE_BY_ID), param);
        });
    }

重现步骤(如果有就写完整)

报错信息

weitangli avatar May 27 '22 02:05 weitangli

count 就多了一次查询了

qmdx avatar May 30 '22 15:05 qmdx

count 就多了一次查询了

没理解,在哪里会多产生一次查询? 我的理解是CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_BY_ID), entity))只是用来判断这个idVal对应的数据是否真的存在于数据库中,没看到其他作用。

weitangli avatar May 31 '22 01:05 weitangli

这个方法有一个问题当表里不存在数据的时候并没有去Save会一直执行SelectById直到报stackoverflowerror

yjia0 avatar Jun 15 '22 11:06 yjia0

这个方法有一个问题当表里不存在数据的时候并没有去Save会一直执行SelectById直到报stackoverflowerror

本人用的3.4.3.4

yjia0 avatar Jun 15 '22 11:06 yjia0

这个方法有一个问题当表里不存在数据的时候并没有去Save会一直执行SelectById直到报stackoverflowerror

使用最新版本 3.5.3 如果还存在问题,请给我 一个 demo 演示重复该问题,重新发一个 issue 谢谢

qmdx avatar Dec 29 '22 02:12 qmdx