mybatis-plus
mybatis-plus copied to clipboard
saveOrUpdate 和 saveOrUpdateBatch 优化
当前使用版本(必填,否则不予处理)
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);
});
}
重现步骤(如果有就写完整)
报错信息
count 就多了一次查询了
count 就多了一次查询了
没理解,在哪里会多产生一次查询?
我的理解是CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_BY_ID), entity))
只是用来判断这个idVal
对应的数据是否真的存在于数据库中,没看到其他作用。
这个方法有一个问题当表里不存在数据的时候并没有去Save会一直执行SelectById直到报stackoverflowerror
这个方法有一个问题当表里不存在数据的时候并没有去Save会一直执行SelectById直到报stackoverflowerror
本人用的3.4.3.4
这个方法有一个问题当表里不存在数据的时候并没有去Save会一直执行SelectById直到报stackoverflowerror
使用最新版本 3.5.3 如果还存在问题,请给我 一个 demo 演示重复该问题,重新发一个 issue 谢谢