通过主键ID批量更新list
主要通过CASE WHEN END来实现
此类UpdateBatch
为具体实现:
public class UpdateBatch extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
String sqlTemp = "<script>UPDATE %s %s WHERE %s in %s</script>";
String whereSql = "<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\",\" close=\")\">#{item."+tableInfo.getKeyProperty()+"}</foreach>";
StringBuilder sb = new StringBuilder("set ");
for (TableFieldInfo tableFieldInfo : tableInfo.getFieldList()) {
sb.append(tableFieldInfo.getColumn()).append(" = case ").append(tableInfo.getKeyColumn());
sb.append(" <foreach item='item' index='index' collection='list' > ");
sb.append(" WHEN #{item." + tableInfo.getKeyProperty() + "}");
sb.append(" <if test='item."+tableFieldInfo.getProperty()+"!=null'> ");
sb.append(" THEN #{item."+ tableFieldInfo.getProperty() +"} </if> ");
sb.append(" <if test='item."+tableFieldInfo.getProperty()+"==null'> ");
sb.append(" THEN "+ tableFieldInfo.getColumn() + "</if> ");
sb.append(" </foreach> end,");
}
// 删除最后一个,逗号
String setSql = sb.toString().substring(0, sb.toString().length()-1);
String sql = String.format(sqlTemp, tableInfo.getTableName(), setSql, tableInfo.getKeyColumn(),
whereSql);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return this.addUpdateMappedStatement(mapperClass, modelClass, "updateBatch", sqlSource);
}
}
public class MySqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
//增加自定义方法
methodList.add(new UpdateBatch());
/**
* 以下 3 个为内置选装件
* 头 2 个支持字段筛选函数
*/
// 例: 不要指定了 update 填充的字段
methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
methodList.add(new AlwaysUpdateSomeColumnById());
methodList.add(new LogicDeleteByIdWithFill());
return methodList;
}
}
public interface MyBaseMapper<T> extends BaseMapper<T> {
/* ↓↓↓↓↓↓↓↓↓↓↓↓↓↓ ↓↓↓↓↓↓↓↓↓↓↓↓↓↓ */
/**
* 以下定义的 4个 default method, copy from {@link com.baomidou.mybatisplus.extension.toolkit.ChainWrappers}
*/
default QueryChainWrapper<T> queryChain() {
return new QueryChainWrapper<>(this);
}
default LambdaQueryChainWrapper<T> lambdaQueryChain() {
return new LambdaQueryChainWrapper<>(this);
}
default UpdateChainWrapper<T> updateChain() {
return new UpdateChainWrapper<>(this);
}
default LambdaUpdateChainWrapper<T> lambdaUpdateChain() {
return new LambdaUpdateChainWrapper<>(this);
}
/**
* 以下定义的 4个 method 其中 3 个是内置的选装件
*/
int insertBatchSomeColumn(List<T> entityList);
int alwaysUpdateSomeColumnById(@Param(Constants.ENTITY) T entity);
int deleteByIdWithFill(T entity);
/**
* 以下为自定义 批量更新方法
*/
int updateBatch(@Param("list") List<T> list);
}
配置bean(基本操作):
@Configuration
public class MybatisPlusConfig {
@Bean
public MySqlInjector sqlInjector() {
return new MySqlInjector();
}
}