基于mybatis batch實(shí)現(xiàn)批量提交大量數(shù)據(jù)
很多人在用 MyBatis 或者 通用 Mapper 時(shí),經(jīng)常會(huì)問有沒有批量插入和批量更新的方法。
實(shí)際上許多時(shí)候沒必要用 <foreach> 去實(shí)現(xiàn)特別復(fù)雜的批量操作。直接通過 MyBatis 的 BATCH 方式執(zhí)行增刪改方法即可。
下面是一個(gè)批量用法的例子:
在xml文件配置多條參數(shù)同時(shí)插入:
<insert parameterType='ctas.entity.SharkFlt'> <selectKey keyProperty='recId' order='BEFORE' resultType='Long'> select SEQ_CTAS_SHARK_FLT.nextval as recId from dual </selectKey> insert into CTAS_SHARK_FLT (<include refid='Base_Column_List'/>) SELECT SEQ_TEST.NEXTVAL, A.* FROM ( <foreach collection='list' item='item' index='index' open='' close='' separator='union all'> select #{item.awbType,jdbcType=VARCHAR}, #{item.awbPre,jdbcType=VARCHAR},... from dual </foreach> ) A </insert>
在Java代碼中,oracle中一次執(zhí)行的sql語句長度是有限制的,如果最后拼出來的sql字符串過長,會(huì)導(dǎo)致執(zhí)行失敗,所以java端還要做一個(gè)分段處理,參考下面的處理:
List<SharkFlt> data = new ArrayList<SharkFlt>(); for (TSharkFlt f : sharkFlts) { data.add(getSharkFlt(f)); } System.out.println(data.size()); long beginTime = System.currentTimeMillis(); System.out.println('開始插入...'); SqlSessionFactory sqlSessionFactory =ctx.getBean(SqlSessionFactory.class); SqlSession session = null; try { session = sqlSessionFactory.openSession(ExecutorType.BATCH, false); int a = 2000;//每次提交2000條 int loop = (int) Math.ceil(data.size() / (double) a);List<SharkFlt> tempList = new ArrayList<SharkFlt>(a); int start, stop; for (int i = 0; i < loop; i++) {tempList.clear();start = i * a;stop = Math.min(i * a + a - 1, data.size() - 1);System.out.println('range:' + start + ' - ' + stop);for (int j = start; j <= stop; j++) { tempList.add(data.get(j));} session.insert('ctas.importer.writer.mybatis.mappper.SharkFltMapper.insertBatch2', tempList);session.commit();session.clearCache(); System.out.println('已經(jīng)插入' + (stop + 1) + ' 條'); } } catch (Exception e) { e.printStackTrace(); session.rollback(); } finally { if (session != null) {session.close(); } } long endTime = System.currentTimeMillis(); System.out.println('插入完成,耗時(shí) ' + (endTime - beginTime) + ' 毫秒!');
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Windows下在DOS用mysql命令行導(dǎo)入.sql文件2. Microsoft Office Access添加頁眉或頁腳的方法3. MySQL中 concat函數(shù)的使用4. MySQL數(shù)據(jù)庫連接異常匯總(值得收藏)5. Oracle數(shù)據(jù)庫備份與恢復(fù)之完全攻略6. 帶你學(xué)習(xí)MySQL執(zhí)行計(jì)劃7. MySQL之mysqldump的使用詳解8. 通過Backup Exec實(shí)施Oracle來災(zāi)難恢復(fù)9. 快速解決mysql導(dǎo)出scv文件亂碼、躥行的問題10. 用IE遠(yuǎn)程創(chuàng)建Mysql數(shù)據(jù)庫的簡易程序
