批量插入使用注意点
一、mysql连接
- jdbc url 加上
&rewriteBatchedStatements=true
二、注意使用
- 推荐 使用
mapper
的 dbSaveBatch
,性能强劲,默认1000一个批次,可修改单次提交条数,严禁超过5000
- 10000条 5000条一批次,测试插入0.559秒
- 10000条 2000条一批次,测试插入0.770秒
@Test
public void test08() {
List<Device> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
Device device = new Device();
device.setType(2L + i);
list.add(device);
}
long l = System.currentTimeMillis();
System.out.println(deviceMapper.dbSaveBatch(list,5000));
System.out.println(System.currentTimeMillis() - l + " ms");
System.out.printf("");
}
@Test
public void test08() {
List<Device> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
Device device = new Device();
device.setType(2L + i);
list.add(device);
}
long l = System.currentTimeMillis();
deviceService.saveBatch(list);
System.out.println(System.currentTimeMillis() - l + " ms");
System.out.printf("");
}
三、Mapper层代码
public interface ProMapper<T extends BaseEntity> extends MPJBaseMapper<T> {
default boolean dbSaveBatch(Collection<T> entityList) {
return Db.saveBatch(entityList);
}
default boolean dbSaveBatch(Collection<T> entityList, int batchSize) {
return batchSize <= 5000 && Db.saveBatch(entityList, batchSize);
}
}