尽管mybatis
有BatchExecutor
,但还是比jdbc executeBatch
慢多了。
/**
* 批量插入用jdbc更快
*/
@SpringBootTest
public class BatchInsertTest {
@Autowired
private DataSource dataSource;
@Autowired
private SqlSessionFactory sqlSessionFactory;
/**
* 测试mybatis(BatchExecutor)插入1万条数据的时间 => 22s
*/
@Test
public void test_batchInsert_mybatis() {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
UserMapper2 userMapper2 = sqlSession.getMapper(UserMapper2.class);
try {
long start = System.currentTimeMillis();
int lastId = userMapper2.getLastId();
for (int i = 0; i < 10000; ++i) {
userMapper2.insert(new User(lastId + i + 1, "mybatis", "mybatis", null));
}
sqlSession.commit();
long end = System.currentTimeMillis();
System.out.format("%d s\n", (end - start) / 1000);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("回滚");
sqlSession.rollback();
} finally {
sqlSession.close();
}
}
/**
* 测试jdbc插入1万条数据的时间 => 3s
*/
@Test
public void test_batchInsert_jdbc() throws SQLException {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.SIMPLE);
UserMapper2 userMapper2 = sqlSession.getMapper(UserMapper2.class);
int lastId = userMapper2.getLastId();
Connection connection = dataSource.getConnection();
connection.setAutoCommit(false);
String sql = "INSERT INTO user (id,username,password,did) VALUES(?,?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
for (int i = 0; i < 10000; ++i) {
statement.setLong(1, lastId + i + 1);
statement.setString(2, "jdbc");
statement.setString(3, "jdbc");
statement.setString(4, null);
statement.addBatch();
}
long start = System.currentTimeMillis();
statement.executeBatch();
connection.commit();
long end = System.currentTimeMillis();
System.out.format("%d s\n", (end - start) / 1000);
statement.close();
connection.close();
}
}