mybatis-plus根据指定条件批量更新

1.service实现类中

比如我这里只针对UserEntity,在UserServiceImpl下(该实现类是继承了mybatis-plus的ServiceImpl的)新增如下代码:

java 复制代码
public boolean updateBatchByQueryWrapper(Collection<UserEntity> entityList, Function<UserEntity, QueryWrapper> queryWrapperFunction) {
    String sqlStatement = this.getSqlStatement(SqlMethod.UPDATE);
    return this.executeBatch(entityList, DEFAULT_BATCH_SIZE, (sqlSession, entity) -> {
        ParamMap param = new ParamMap();
        param.put(Constants.ENTITY, entity);
        param.put(Constants.WRAPPER, queryWrapperFunction.apply(entity));
        sqlSession.update(sqlStatement, param);
    });
}

1)这里使用了Function函数式接口,如果不知道请查看Java函数式编程入门学习举例与优点详解

2)batchSize这里默认使用DEFAULT_BATCH_SIZE,也是mybatis-plus中的默认值1000,当然你也可以保留该入参

3)主要核心的修改地方是以下两部分:

java 复制代码
// SqlMethod.UPDATE_BY_ID改为SqlMethod.UPDATE
String sqlStatement = this.getSqlStatement(SqlMethod.UPDATE);
//和新增如下的wapper,即更新条件
param.put(Constants.WRAPPER, queryWrapperFunction.apply(entity));

2.调用时

java 复制代码
userService.updateBatchByQueryWrapper(userList, user->new QueryWrapper<>().eq("username",user.getUsername()));

3. 参考文章

相关推荐
tycooncool2 小时前
Spring Boot中集成MyBatis操作数据库详细教程
数据库·spring boot·mybatis
一只大袋鼠16 小时前
MyBatis 入门详细实战教程(一):从环境搭建到查询运行
java·开发语言·数据库·mysql·mybatis
Full Stack Developme21 小时前
MyBatis-Plus 流式查询教程
前端·python·mybatis
ccice011 天前
全面掌握Spring Boot + MyBatis + Maven + MySQL:从开发到部署的后端技术详解
spring boot·maven·mybatis
消失的旧时光-19431 天前
Spring Boot + MyBatis 从 0 到 1 跑通查询接口(含全部踩坑)
spring boot·后端·spring·mybatis
1.14(java)1 天前
MyBatis 操作数据库
数据库·mybatis
杰克尼2 天前
天机学堂项目总结(day1~day2)
大数据·jvm·spring·elasticsearch·搜索引擎·spring cloud·mybatis
Java成神之路-2 天前
SpringBoot 整合 SSM 全流程详解(含 JUnit+MyBatis 实战)(Spring系列18)
spring boot·junit·mybatis
时间静止不是简史2 天前
当MyBatis-Plus的like遇上SQL通配符:下划线翻车记
java·sql·mybatis
夕除2 天前
javaweb--10
mybatis