不灭的火

革命尚未成功,同志仍须努力下载JDK17

作者:AlbertWen  添加时间:2022-05-15 23:43:53  修改时间:2025-05-17 14:26:06  分类:07.Java框架/系统  编辑

MyBatis-Plus 的学习成本相对较低,当学会了MyBatis之后,MyBatis-Plus很有友好的,对MyBatis仅仅是增强,没有任何改变,学习难度较低。

其中有个小小的问题,即 IService中自带的 saveBatchsaveOrUpdateBatch 等方法,仔细看会发现,他们的批量执行,竟然不是 真正的(数据库级别的)批量执行!!!

附:MySQL批量处理大数据:

  1. MySQL的批量插入数据
  2. MySQL的批量修改数据

IService 的实现类 ServiceImpl 中截取一段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
 * 批量插入
 *
 * @param entityList ignore
 * @param batchSize  ignore
 * @return ignore
 */
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveBatch(Collection<T> entityList, int batchSize) {
    String sqlStatement = getSqlStatement(SqlMethod.INSERT_ONE);
    return executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));
}

会发现,其实是在循环插入,那么如果这样,我们有两种选择

  1. 使用MyBatis 的xml文件,自己拼接插入,修改语句,就像最原始的那样,通过<foreach>标签实现
  2. 重新配置全局的批量修改、增加方法

第一种不再赘述,现在说说第二种用法

一共需要五步:

第一步:一般引入MyBatis-Plus 都会有相应的配置类,MyBatisPlusConfig 名字无所谓,作用是一样的,一般都会用自带的分页插件,可以在此基础上,继续添加,给出我的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 分页插件
@Configuration
public class MyBatisPlusConfig {
    @Bean
    @ConditionalOnMissingBean
    public MyBatisPlusInterceptor MyBatisPlusInterceptor() {
        MyBatisPlusInterceptor paginationInterceptor = new MyBatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor= new PaginationInnerInterceptor(DbType.MYSQL);
        paginationInterceptor.addInnerInterceptor(paginationInnerInterceptor);
        return paginationInterceptor;
    }
  
    // 自定义Sql注入器
    @Bean
    public MySqlInjector mySqlInjector() {
        return new MySqlInjector();
    }
  
}

第二步:创建自定义sql注入器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.wanma.framework_web.plugin.mybatisplus;
 
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
 
import java.util.List;
 
/**
 * 自定义方法SQL注入器
 * 【注意】这个类名,可以随便命名
 */
public class MySqlInjector extends DefaultSqlInjector {
    /**
     * 如果只需增加方法,保留MyBatis plus自带方法,
     * 可以先获取super.getMethodList(),再添加add
     */
    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
        methodList.add(new InsertBatchMethod());
        methodList.add(new UpdateBatchMethod());
        return methodList;
    }
}

第三步:创建一个类似于MyBatis-Plus 中的 BaseMapper的一个接口,我这里叫做RootMapper,然后继承BaseMapper,并新增两个批量操作方法:insertBatch 和 updateBatch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * 使用的时候,只需要继承RootMapper即可
 */
public interface RootMapper<T> extends BaseMapper<T> {
  
    /**
     * 自定义批量插入
     * 如果要自动填充,@Param(xx) xx参数名必须是 list/collection/array 3个的其中之一
     */
    int insertBatch(@Param("list") List<T> list);
  
    /**
     * 自定义批量更新,条件为主键
     * 如果要自动填充,@Param(xx) xx参数名必须是 list/collection/array 3个的其中之一
     */
    int updateBatch(@Param("list") List<T> list);
  
}

第四步:分别创建上述两个方法的具体实现类

(1)批量新增

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@Slf4j
public class InsertBatchMethod extends AbstractMethod {
    /**
     * insert into user(id, name, age) values (1, "a", 17), (2, "b", 18);
     <script>
     insert into user(id, name, age) values
     <foreach collection="list" item="item" index="index" open="(" separator="),(" close=")">
          #{item.id}, #{item.name}, #{item.age}
     </foreach>
     </script>
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        final String sql = "<script>insert into %s %s values %s</script>";
        final String fieldSql = prepareFieldSql(tableInfo);
        final String valueSql = prepareValuesSql(tableInfo);
        final String sqlResult = String.format(sql, tableInfo.getTableName(), fieldSql, valueSql);
        log.debug("sqlResult----->{}", sqlResult);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
        // 第三个参数必须和RootMapper的自定义方法名一致
        return this.addInsertMappedStatement(mapperClass, modelClass, "insertBatch", sqlSource, new NoKeyGenerator(), null, null);
    }
  
    private String prepareFieldSql(TableInfo tableInfo) {
        StringBuilder fieldSql = new StringBuilder();
        fieldSql.append(tableInfo.getKeyColumn()).append(",");
        tableInfo.getFieldList().forEach(x -> {
            fieldSql.append(x.getColumn()).append(",");
        });
        fieldSql.delete(fieldSql.length() - 1, fieldSql.length());
        fieldSql.insert(0, "(");
        fieldSql.append(")");
        return fieldSql.toString();
    }
  
    private String prepareValuesSql(TableInfo tableInfo) {
        final StringBuilder valueSql = new StringBuilder();
        valueSql.append("<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\"),(\" close=\")\">");
        valueSql.append("#{item.").append(tableInfo.getKeyProperty()).append("},");
        tableInfo.getFieldList().forEach(x -> valueSql.append("#{item.").append(x.getProperty()).append("},"));
        valueSql.delete(valueSql.length() - 1, valueSql.length());
        valueSql.append("</foreach>");
        return valueSql.toString();
    }
}

(2)批量修改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * 批量更新方法实现,条件为主键,选择性更新
 */
@Slf4j
public class UpdateBatchMethod extends AbstractMethod {
    /**
     * update user set name = "a", age = 17 where id = 1;
     * update user set name = "b", age = 18 where id = 2;
     <script>
        <foreach collection="list" item="item" separator=";">
            update user
            <set>
                <if test="item.name != null and item.name != ''">
                    name = #{item.name,jdbcType=VARCHAR},
                </if>
                <if test="item.age != null">
                    age = #{item.age,jdbcType=INTEGER},
                </if>
            </set>
            where id = #{item.id,jdbcType=INTEGER}
        </foreach>
     </script>
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = "<script>\n<foreach collection=\"list\" item=\"item\" separator=\";\">\nupdate %s %s where %s=#{%s} %s\n</foreach>\n</script>";
        String additional = tableInfo.isWithVersion() ? tableInfo.getVersionFieldInfo().getVersionOli("item", "item.") : "" + tableInfo.getLogicDeleteSql(true, true);
        String setSql = sqlSet(tableInfo.isWithLogicDelete(), false, tableInfo, false, "item", "item.");
        String sqlResult = String.format(sql, tableInfo.getTableName(), setSql, tableInfo.getKeyColumn(), "item." + tableInfo.getKeyProperty(), additional);
        log.debug("sqlResult----->{}", sqlResult);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
        // 第三个参数必须和RootMapper的自定义方法名一致
        return this.addUpdateMappedStatement(mapperClass, modelClass, "updateBatch", sqlSource);
    }
  
}

第五步:使用,将原有的继承BaseMapper的方法,改写为继承RootMapper,后续批量操作,直接使用新增的两个方法进行处理即可。

 

 

参考:

【MyBatis-Plus】批量插入数据

2022-05-05 MyBatis-plus 批量插入修改操作