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

1.service实现类中

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

public boolean updateBatchByQueryWrapper(Collection entityList, Function 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)主要核心的修改地方是以下两部分:

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

2.调用时

userService.updateBatchByQueryWrapper(userList, user->new QueryWrapper<>().eq("username",user.getUsername()));

3. 参考文章

你可能感兴趣的:(mybatis)