最近需要用到大数据量的数据同步,闲来没事做了一次小小的测试,话不多说代码以及结果走起:
首先我随便建了一张表如下

mapper接口中的代码:
@Insert("insert into p_table values (#{name},#{lastName},#{fistName})")
int batchInsert(PTable pTable);
@Insert("<script>insert into p_table values" +
" <foreach collection=\"pTables\" item=\"album\" separator=\",\" close=\";\">" +
" (#{album.name},#{album.lastName},#{album.fistName})" +
"</foreach></script>")
int foreachInsert(List<PTable> pTables);
batchInsert插入
static SqlSessionFactory sqlSessionFactory;
public static SqlSessionFactory getSessionFaction() {
if (sqlSessionFactory == null) {
sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
} else {
return sqlSessionFactory;
}
return sqlSessionFactory;
}
@Test
void batchInsert() {
String name="xiao,ming";
List<PTable> pTables=new ArrayList<>();
for (int i = 0; i < 1000; i++) {
pTables.add(new PTable(name+i,name.split(",")[0],name.split(",")[1]));
}
SqlSession sqlSession=getSessionFaction().openSession(ExecutorType.BATCH);
PTableMapper pTableMapper=sqlSession.getMapper(PTableMapper.class);
Long startTime=System.currentTimeMillis();
pTables.forEach(pTableMapper::batchInsert);
sqlSession.commit();
sqlSession.close();
Long endTime=System.currentTimeMillis();
System.out.println("所用时间"+(endTime-startTime)+"毫秒");
}
foreach批量插入
@Test
void foreachInsert(){
String name="xiao,ming";
List<PTable> pTables=new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
pTables.add(new PTable(name+i,name.split(",")[0],name.split(",")[1]));
}
Long startTime=System.currentTimeMillis();
pTableMapper.foreachInsert(pTables);
Long endTime=System.currentTimeMillis();
System.out.println("所用时间"+(endTime-startTime)+"毫秒");
}
for循环插入
@Test
void forInsert(){
String name="xiao,ming";
List<PTable> pTables=new ArrayList<>();
for (int i = 0; i < 10000; i++) {
pTables.add(new PTable(name+i,name.split(",")[0],name.split(",")[1]));
}
Long startTime=System.currentTimeMillis();
pTables.forEach(pTable -> pTableMapper.batchInsert(pTable));
Long endTime=System.currentTimeMillis();
System.out.println("所用时间"+(endTime-startTime)+"毫秒");
}
所用时间分别如下
插入条数/方法 | batchInsert | foreach | for循环插入 |
1000条 | 241毫秒 | 461毫秒 | 1633毫秒 |
10000条 | 424毫秒 | 667毫秒 | 10125毫秒 |
1000000条 | 30514毫秒 | 47098毫秒 | _ |
以上仅是个人做了一个小小的实验,有什么缺陷和错误欢迎大家的指正,总体来说这波测试还是batchInsert方法略胜一筹啊。