Mybatis Plus 真正批量插入

、Mybatis Plus默认批量插入saveBatch方法在IService中,是使用同一个sqlSession,这相比遍历集合循环insert来说有一定的性能提升,但是这并不是sql层面真正的批量插入。
Mybatis Plus 真正批量插入_第1张图片
、jdbc添加rewriteBatchedStatements=true 无法改变本质

、真正批量插入

继承DefaultSqlInjector自定义sql注入器

public class MySqlInjector extends DefaultSqlInjector {

    @Override
    public List<AbstractMethod> getMethodList(Class<?> mapperClass, TableInfo tableInfo) {
        List<AbstractMethod> methodList = super.getMethodList(mapperClass, tableInfo);
        //更新时自动填充的字段,不用插入值
        methodList.add(new InsertBatchSomeColumn(i -> i.getFieldFill() != FieldFill.UPDATE));
        return methodList;
    }

}

将自定义的sql注入器注入到Mybatis容器中

@Configuration
public class MybatisPlusConfig {
	@Bean
    public MySqlInjector sqlInjector() {
        return new MySqlInjector();
    }
}

继承 BaseMapper 添加自定义方法

public interface CommonMapper<T> extends BaseMapper<T> {
    /**
     * 真正的批量插入
     * @param entityList
     * @return
     */
    int insertBatchSomeColumn(List<T> entityList);

}

Mapper继承CommonMapper接口,调用insertBatchSomeColumn方法

你可能感兴趣的:(mybatis)