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

相关推荐
Mr_pyx1 小时前
面试题记录
jvm·数据结构·算法·spring·mybatis
摇滚侠5 小时前
Mybatis 面试题 真正的 offer 偏方 Java 基础 Java 高级
java·开发语言·mybatis
Devin~Y5 小时前
大厂Java面试实录:Spring Boot/Cloud + Redis + Kafka + JVM + RAG(Spring AI)三轮追问(小Y翻车版)
java·jvm·spring boot·redis·spring cloud·kafka·mybatis
月落归舟15 小时前
一篇文章了解Redis内存淘汰机制与过期Key清理
数据库·redis·mybatis
Devin~Y1 天前
大厂Java面试实录:Spring Boot/WebFlux、JVM调优、Redis/Kafka、Spring Cloud 与 RAG/Agent 追问
java·jvm·spring boot·maven·mybatis·jpa·spring webflux
Boop_wu1 天前
[Java项目] Spring Boot + WebSocket 实现网页在线聊天室|完整项目架构与实战讲解
spring boot·websocket·java-ee·mybatis
IronMurphy2 天前
Redis拷打第三讲
数据库·redis·mybatis
小坏讲微服务2 天前
SpringBoot4.0整合Spring Security+MyBatis Plus完整权限框架实现
java·spring·mybatis·spring security·mybatis plus·springboot4.0
静小谢2 天前
sql笔记
spring boot·笔记·sql·mybatis
桔筐2 天前
MyBatis-Plus Service/ServiceImpl/IService 核心关系
mybatis