MyBatis文檔中寫批量插入的時(shí)候谆膳,是推薦使用另外一種方法懂衩。(可以看 http://www.mybatis.org/mybatis-dynamic-sql/docs/insert.html 中 Batch Insert Support 標(biāo)題里的內(nèi)容)
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();
}
即基本思想是將 MyBatis session 的 executor type 設(shè)為 Batch ,然后多次執(zhí)行插入語(yǔ)句愿吹。就類似于JDBC的下面語(yǔ)句一樣不从。
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=UTF-8&useServerPrepStmts=false&rewriteBatchedStatements=true","root","root");
connection.setAutoCommit(false);
PreparedStatement ps = connection.prepareStatement(
"insert into tb_user (name) values(?)");
for (int i = 0; i < stuNum; i++) {
ps.setString(1,name);
ps.addBatch();
}
ps.executeBatch();
connection.commit();
connection.close();
經(jīng)過(guò)試驗(yàn),使用了 ExecutorType.BATCH 的插入方式犁跪,性能顯著提升椿息,不到 2s 便能全部插入完成。
總結(jié)一下坷衍,如果MyBatis需要進(jìn)行批量插入寝优,推薦使用 ExecutorType.BATCH 的插入方式,如果非要使用 <foreach>的插入的話枫耳,需要將每次插入的記錄控制在 20~50 左右乏矾。
<insert id="batchInsert" parameterType="java.util.List">
insert into USER (id, name) values
<foreach collection="list" item="model" index="index" separator=",">
(#{model.id}, #{model.name})
</foreach>
</insert> ```