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

相关推荐
while(1){yan}29 分钟前
Spring事务
java·数据库·spring boot·后端·java-ee·mybatis
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧2 小时前
《苍穹外卖》- day01 开发环境搭建
spring boot·后端·spring·maven·intellij-idea·mybatis
曹轲恒2 小时前
@PropertySource、@ImportResource、@Bean
java·spring boot·mybatis
程序员侠客行11 小时前
Spring集成Mybatis原理详解
java·后端·spring·架构·mybatis
tqs_1234514 小时前
@transactional事务失效场景
java·数据库·mybatis
小北方城市网14 小时前
Spring Cloud Gateway实战:路由、限流、熔断与鉴权全解析
java·spring boot·后端·spring·mybatis
huohuopro1 天前
Mybatis的七种传参方式
java·开发语言·mybatis
sunnyday04261 天前
Spring Boot 自定义 Starter 实战:从创建到使用的完整指南
spring boot·后端·mybatis
小北方城市网1 天前
Redis 分布式锁与缓存三大问题解决方案
spring boot·redis·分布式·后端·缓存·wpf·mybatis
Dontla1 天前
Mybatis Introduction (Java ORM Framework)
java·开发语言·mybatis