mysql批量插入常用foreach的方式,但是经过项目实践发现,当表的列数较多(20+),以及一次性插入的行数较多(5000+)时,整个插入的耗时十分漫长。
方法1:这时我们可以考虑减少一条 insert 语句中 values 的个数,大概在10~100行,使速度最快。一般按经验来说,一次性插20~50行数量是比较合适的,时间消耗也能接受。
方法2:根据MyBatis文档中写批量插入的时候,是推荐使用另外一种方法,将MyBatis session 的 executor type 设为 Batch ,然后多次执行插入语句。(参考 http://www.mybatis.org/mybatis-dynamic-sql/docs/insert.html 中 Batch Insert Support 的内容)
SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
try {
SimpleTableMapper mapper = session.getMapper(SimpleTableMapper.class);
List<SimpleTableRecord> records = getRecordsToInsert(); // not shown
BatchInsert<SimpleTableRecord> batchInsert = insert(records)
.into(simpleTable)
.map(id).toProperty("id")
.map(firstName).toProperty("firstName")
.map(lastName).toProperty("lastName")
.map(birthDate).toProperty("birthDate")
.map(employed).toProperty("employed")
.map(occupation).toProperty("occupation")
.build()
.render(RenderingStrategy.MYBATIS3);
batchInsert.insertStatements().stream().forEach(mapper::insert);
session.commit();
} finally {
session.close();
}
参考资料
- http://www.mybatis.org/mybatis-dynamic-sql/docs/insert.html