后端技术:MyBatis 批量插入的 3 种写法
運行環境:
數據庫使用的是sqlserver,JDK版本1.8,運行在SpringBoot環境下,對比3種可用的方式:
反復執行單條插入語句
xml拼接sql
批處理執行
先說結論:少量插入請使用反復插入單條數據,方便。數量較多請使用批處理方式。
(可以考慮以有需求的插入數據量20條左右為界吧,在我的測試和數據庫環境下耗時都是百毫秒級的,方便最重要)。無論何時都不用xml拼接sql的方式。
代碼
拼接SQL的xmlnewId()是sqlserver生成UUID的函數,與本文內容無關
<insert?id="insertByBatch"?parameterType="java.util.List">INSERT?INTO?tb_item?VALUES<foreach?collection="list"?item="item"?index="index"?separator=",">(newId(),#{item.uniqueCode},#{item.projectId},#{item.name},#{item.type},#{item.packageUnique},#{item.isPackage},#{item.factoryId},#{item.projectName},#{item.spec},#{item.length},#{item.weight},#{item.material},#{item.setupPosition},#{item.areaPosition},#{item.bottomHeight},#{item.topHeight},#{item.serialNumber},#{item.createTime}</foreach> </insert>Mapper接口
Mapper是 mybatis插件tk.Mapper 的接口,與本文內容關系不大
public?interface?ItemMapper?extends?Mapper<Item>?{int?insertByBatch(List<Item>?itemList); }Service類
@Service public?class?ItemService?{@Autowiredprivate?ItemMapper?itemMapper;@Autowiredprivate?SqlSessionFactory?sqlSessionFactory;//批處理@Transactionalpublic?void?add(List<Item>?itemList)?{SqlSession?session?=?sqlSessionFactory.openSession(ExecutorType.BATCH,false);ItemMapper?mapper?=?session.getMapper(ItemMapper.class);for?(int?i?=?0;?i?<?itemList.size();?i++)?{mapper.insertSelective(itemList.get(i));if(i%1000==999){//每1000條提交一次防止內存溢出session.commit();session.clearCache();}}session.commit();session.clearCache();}//拼接sql@Transactionalpublic?void?add1(List<Item>?itemList)?{itemList.insertByBatch(itemMapper::insertSelective);}//循環插入@Transactionalpublic?void?add2(List<Item>?itemList)?{itemList.forEach(itemMapper::insertSelective);} }測試類
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment?=?SpringBootTest.WebEnvironment.RANDOM_PORT,?classes?=?ApplicationBoot.class) public?class?ItemServiceTest?{@AutowiredItemService?itemService;private?List<Item>?itemList?=?new?ArrayList<>();//生成測試List@Before?public?void?createList(){String?json?="{\n"?+"????????\"areaPosition\":?\"TEST\",\n"?+"????????\"bottomHeight\":?5,\n"?+"????????\"factoryId\":?\"0\",\n"?+"????????\"length\":?233.233,\n"?+"????????\"material\":?\"Q345B\",\n"?+"????????\"name\":?\"TEST\",\n"?+"????????\"package\":?false,\n"?+"????????\"packageUnique\":?\"45f8a0ba0bf048839df85f32ebe5bb81\",\n"?+"????????\"projectId\":?\"094b5eb5e0384bb1aaa822880a428b6d\",\n"?+"????????\"projectName\":?\"項目_TEST1\",\n"?+"????????\"serialNumber\":?\"1/2\",\n"?+"????????\"setupPosition\":?\"1B柱\",\n"?+"????????\"spec\":?\"200X200X200\",\n"?+"????????\"topHeight\":?10,\n"?+"????????\"type\":?\"Steel\",\n"?+"????????\"uniqueCode\":?\"12344312\",\n"?+"????????\"weight\":?100\n"?+"????}";Item?test1?=?JSON.parseObject(json,Item.class);test1.setCreateTime(new?Date());for?(int?i?=?0;?i?<?1000;?i++)?{//測試會修改此數量itemList.add(test1);}}//批處理@Test@Transactionalpublic?void?tesInsert()?{itemService.add(itemList);}//拼接字符串@Test@Transactionalpublic?void?testInsert1(){itemService.add1(itemList);}//循環插入@Test@Transactionalpublic?void?testInsert2(){itemService.add2(itemList);} }測試結果:
10條 25條數據插入經多次測試,波動性較大,但基本都在百毫秒級別
其中 拼接sql方式在插入500條和1000條時報錯(似乎是因為sql語句過長,此條跟數據庫類型有關,未做其他數據庫的測試):
com.microsoft.sqlserver.jdbc.SQLServerException: 傳入的表格格式數據流(TDS)遠程過程調用(RPC)協議流不正確。此 RPC 請求中提供了過多的參數。最多應為 2100可以發現
循環插入的時間復雜度是 O(n),并且常數C很大
拼接SQL插入的時間復雜度(應該)是 O(logn),但是成功完成次數不多,不確定
批處理的效率的時間復雜度是 O(logn),并且常數C也比較小
結論
循環插入單條數據雖然效率極低,但是代碼量極少,在使用tk.Mapper的插件情況下,僅需代碼,:
@Transactional public?void?add1(List<Item>?itemList)?{itemList.forEach(itemMapper::insertSelective); }因此,在需求插入數據數量不多的情況下肯定用它了。
xml拼接sql是最不推薦的方式,使用時有大段的xml和sql語句要寫,很容易出錯,工作效率很低。
更關鍵點是,雖然效率尚可,但是真正需要效率的時候你掛了,要你何用?批處理執行是有大數據量插入時推薦的做法,使用起來也比較方便。
IT技術分享社區
個人博客網站:https://programmerblog.xyz
文章推薦程序員效率:畫流程圖常用的工具程序員效率:整理常用的在線筆記軟件遠程辦公:常用的遠程協助軟件,你都知道嗎?51單片機程序下載、ISP及串口基礎知識硬件:斷路器、接觸器、繼電器基礎知識
總結
以上是生活随笔為你收集整理的后端技术:MyBatis 批量插入的 3 种写法的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: Flash Builder 4 正式版序
 - 下一篇: java接口构建英雄属性_Python接