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. 参考文章

相关推荐
❀͜͡傀儡师6 小时前
基于mybatis-plus进行加解密 Spring Boot Starter
spring boot·oracle·mybatis
csdn2015_9 小时前
mybatisplus自动生成id
java·mybatis
xEurCjvwu13 小时前
台达PLC与C#串口通信实现实时同步读写监控功能:配置地址以XML文件为基础动态生成控件
mybatis
LSL666_16 小时前
6 持久化
redis·mybatis·持久化·aof·rdb
哈库纳玛塔塔16 小时前
AI 时代,使用 dbVisitor 读写向量化数据
数据库·人工智能·mybatis
!chen16 小时前
基于 Spring Boot 3.5.x + Sa-Token + MyBatis 企业级文件管理系统
spring boot·后端·mybatis
csdn2015_17 小时前
mybatisplus 获得新增id
java·开发语言·mybatis
无尽的沉默1 天前
SpringBoot整合MyBatis-plus
spring boot·后端·mybatis
PD我是你的真爱粉1 天前
Redis持久化、内存管理、慢查询与发布订阅
redis·python·mybatis
zc.z2 天前
高并发在线考试系统稳定性保障方案
mybatis·高并发