Oracle批处理操作方法
批量更新publicstaticvoidbatchUpdate(SqlSessionFactorysqlSessionFactory,StringmapperStr,List?list){if(listnull||list.isEmpty()){return;}SqlSessionbatchSqlSessionsqlSessionFactory.openSession(ExecutorType.BATCH,false);intbatchSize1000;try{intsizelist.size();for(inti0;isize;i){batchSqlSession.update(mapperStr,list.get(i));// 每 batchSize 条提交一次if((i1)%batchSize0||isize-1){try{batchSqlSession.commit();batchSqlSession.clearCache();}catch(Exceptione){log.error(批次提交失败开始单条重试: {},e.getMessage());// 单条重试intstarti-(i%batchSize);intendi;for(intjstart;jend;j){try{batchSqlSession.update(mapperStr,list.get(j));batchSqlSession.commit();batchSqlSession.clearCache();}catch(Exceptionex){log.error(单条更新失败: {},list.get(j),ex);}}}}}}catch(Exceptione){batchSqlSession.rollback();log.error(批量更新异常,e);throwe;}finally{batchSqlSession.close();}}批量插入importlombok.extern.slf4j.Slf4j;importorg.apache.ibatis.session.ExecutorType;importorg.apache.ibatis.session.SqlSession;importorg.apache.ibatis.session.SqlSessionFactory;Slf4jpublicclassBatchInsertUtil{/** * 通用批量插入和你原batchUpdate逻辑完全一致 * * param sqlSessionFactory sql会话工厂 * param mapperStr mapper全路径方法名如com.xxx.mapper.UserMapper.insert * param list 要插入的数据集合 */publicstaticvoidbatchInsert(SqlSessionFactorysqlSessionFactory,StringmapperStr,List?list){SqlSessionbatchSqlSessionnull;try{// 空集合直接返回if(listnull||list.isEmpty()){return;}// 开启批处理模式手动提交batchSqlSessionsqlSessionFactory.openSession(ExecutorType.BATCH,false);intbatchCount1000;// 每1000条提交一次intbatchLastIndexbatchCount-1;intsizelist.size();intlastIndexsize-1;for(inti0;isize;i){// 执行插入batchSqlSession.insert(mapperStr,list.get(i));// 到达批次末尾 或 最后一条 → 提交if(ilastIndex||ibatchLastIndex){try{// 提交批次batchSqlSession.commit();// 清理缓存防止OOMbatchSqlSession.clearCache();// 下一批次batchLastIndexbatchCount;}catch(Exceptione){log.error(插入批次异常开始单条重试:{},batchLastIndex,e);// 出错 → 本批次降级单条插入intindexbatchLastIndex-batchCount1;for(intjindex;ji;j){try{batchSqlSession.clearCache();batchSqlSession.insert(mapperStr,list.get(j));batchSqlSession.commit();batchSqlSession.clearCache();}catch(Exceptiones){log.error(单条插入失败 mapper:{}数据:{},mapperStr,list.get(j),es);}}batchLastIndexbatchCount;}}}}catch(Exceptionexception){log.error(batchInsert 全局异常:{},exception.getMessage(),exception);if(batchSqlSession!null){batchSqlSession.rollback();}throwexception;}finally{if(batchSqlSession!null){batchSqlSession.close();}}}}