一、业务场景
导入Excel时,当数据量大时,一次一万以上的数据,每次前端返回超时,后台log会一条一条的插入,特别慢1万数据大约需要3~4分钟左右;
二、原因
mybatis提供的批量插入方法saveBatch,但是是伪批量,实质也是一条一条的insert;
为什么会怎么慢呢?mybatis连接数据库默认是自动提交,也就是说insert插入一条提交一次返回自增长id;事务频繁的提交,消耗时间肯定多了;
三、解决
方式一:SQL语句XML中用foreach标签
<insert id="insertBatch">
INSERT INTO tb_student (name, age, phone, address, class_id) VALUES
<foreach collection="list" separator="," item="item">
(#{item.name},#{item.age},#{item.phone},#{item.address},#{item.classId})
</foreach>
</insert>
结果:1万数据大约需要1~2分钟,效率提升,但是一次传输的数据量有限制
方式二:SqlSession中ExecutorType.BATCH并关闭自动提交的方式
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
BeatStandardSmtDao bssd = sqlSession.getMapper(BeatStandardSmtDao.class);
updateList.stream().forEach(beatStandard -> bssd.insertBs(beatStandard));
sqlSession.commit();
sqlSession.clearCache();
sqlSession.close();
结果:10000万条数据只需3~4秒
注意:1)、SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH,false);
2)、在mybatis中不能使用默认的insert()方法,需自己写;--原因默认insert方法会返回自增长的id,但实际我们这里并没有提交,最后一起提交的;
<insert id="insertBs" parameterType="BeatStandardSmtEntity">
INSERT INTO beat_standard_smt (line,family,work_station,avg_beat,udt,editor) VALUES (#{line},#{family},#{workStation},#{avgBeat},#{udt},#{editor})
</insert>
3)、当数据量大时,我们可以分批提交如一万条提交一次;
四、总结
利用底层JDBC中SqlSession,事务提交的方式,将效率提升!
抛砖引玉的记录一下,下次遇到这种问题可以轻松解决,同时也可以帮助同样遇到这种问题的你;