轉載:https://blog.csdn.net/Java_Mr_Zheng/article/details/50476757java
在xml文件配置多條參數同時插入:sql
<insert id="insertBatch2" 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中一次執行的sql語句長度是有限制的,若是最後拼出來的sql字符串過長,會致使執行失敗,因此java端還要作一個分段處理,參考下面的處理:session
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("已經插入" + (stop + 1) + " 條"); } } catch (Exception e) { e.printStackTrace(); session.rollback(); } finally { if (session != null) { session.close(); } } long endTime = System.currentTimeMillis(); System.out.println("插入完成,耗時 " + (endTime - beginTime) + " 毫秒!");