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()));