DevTestOpsGuide

开发 测试 上线 的经验与笔记

View project on GitHub

插入

大规模插入数据时使用批量执行模式

MySQL需在连接参数增加rewriteBatchedStatements=true

Oracle默认支持但不能返回影响条数

spring中代码示例:

    @Autowired
    SqlSessionFactory sqlSessionFactory;

    @Test
    public void insert() throws SQLException {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        TestTableMapper mapper = sqlSession.getMapper(TestTableMapper.class);
        long time = System.currentTimeMillis();
        for (int i = 0; i < 1_000_000; i++) {
            mapper.insert(i);
            if (i % 100_000 == 0) {
                sqlSession.commit();
                LOGGER.info("{}", i);
            }
        }
        sqlSession.commit();
        System.out.println(System.currentTimeMillis() - time);
    }