将传入的实体List分为1000个一批,每个调用sqlSession.insert(sqlStatement, entity),insert完一批做一次
特点:分批插入,batchsize分为一次sql提交
1、继承ServiceImpl
public class AppAttentionServiceImpl extends ServiceImpl implements AppAttentionService {}
2、使用saveBatch
this.saveBatch(infoList);
this.saveBatch(infoList,1000);//每1000个拼接成一个sql进行提交
sqlSession.flushStatements(),看起来是没有问题,但是就是速度非常慢。查阅相关资料发现,要批量执行的话,JDBC连接URL字符串中需要新增一个参数:rewriteBatchedStatements=true
MySQL的JDBC连接的url中要加rewriteBatchedStatements参数,并保证5.1.13以上版本的驱动,才能实现高性能的批量插入。
MySQL JDBC驱动在默认情况下会无视executeBatch()语句,把我们期望批量执行的一组sql语句拆散,一条一条地发给MySQL数据库,批量插入实际上是单条插入,直接造成较低的性能。
只有把rewriteBatchedStatements参数置为true, 驱动才会帮你批量执行SQL
另外这个选项对INSERT/UPDATE/DELETE都有效
解决:
在jdbc连接url最后加上jdbc:mysql://172.29.1.100:5000/bd_cloud_vehicle_dev?rewriteBatchedStatements=true,测试发现速度果然提升
insert into table values (x1, y1, z1), (x2, y2, z2), (x…, y…, z…);
只需要继承BaseMapper就可以有这个方法
特点:拼接成一个sql提交
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;public interface EasyBaseMapper extends BaseMapper {/*** 批量插入 仅适用于mysql* @param entityList 实体列表* @return 影响行数* 注释:这个方法自己编写就好,会有自动提示*/Integer insertBatchSomeColumn(List entityList);
}
其实就是帮我们写了个for循环,一次插入一条数据
特点:逐条插入,适合少量数据插入,或者对性能要求不高的场景
default void insertBatch(Collection entities) {entities.forEach(this::insert);
}
大数据量:InsertBatchSomeColumn > saveBatch > insertBatch