基于mybatis batch實現(xiàn)批量提交大量數(shù)據(jù)
很多人在用 MyBatis 或者 通用 Mapper 時,經(jīng)常會問有沒有批量插入和批量更新的方法。
實際上許多時候沒必要用 <foreach> 去實現(xiàn)特別復(fù)雜的批量操作。直接通過 MyBatis 的 BATCH 方式執(zhí)行增刪改方法即可。
下面是一個批量用法的例子:
在xml文件配置多條參數(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字符串過長,會導(dǎo)致執(zhí)行失敗,所以java端還要做一個分段處理,參考下面的處理:
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('插入完成,耗時 ' + (endTime - beginTime) + ' 毫秒!');
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. MySQL 字符串函數(shù):字符串截取2. DB2高可用性災(zāi)難恢復(fù)(HADR)的限制3. Microsoft Office Access調(diào)整字段位置的方法4. MySQL之mysqldump的使用詳解5. MySQL雙主(主主)架構(gòu)配置方案6. Mybatis Plus插件三種方式的逆向工程的使用7. DB2數(shù)據(jù)庫導(dǎo)出表結(jié)構(gòu)與導(dǎo)入導(dǎo)出表數(shù)據(jù)8. MySQL CHAR和VARCHAR該如何選擇9. mysql group by 對多個字段進(jìn)行分組操作10. 一文帶你學(xué)會Mysql表批量添加字段
