最近有個需求,就是批量處理數據,但是並發量應該很大,當時第一時間想到得是mybatis的foreach去處理,但是后來通過查資料發現,相對有spring 的jdbcTemplate處理速度,mybatis還是有些慢,后來就自己重寫了一下jdbcTemplate的批量處理代碼:
public void batchCarFlowInsert(List<FlowCarReportDayBo> list) { String sql =" INSERT INTO flow_report_day (id, park_number, park_name, start_time, nature_sum_count, " + " temp_car_count, vip_car_count, in_car_count, out_car_count, charge_sum_count, charge_car_count, " + " free_car_count, discount_sum_count, discount_local_car_count, discount_bussiness_car_count, " + " visit_in_car_count, visit_out_car_count, black_in_car_count, black_out_car_count) " + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "; List<Object[]> args = transformFlowCarReportDayBoToObjects(list); int fromIndex = 0; int toIndex = BATCH_SIZE; while (fromIndex != args.size()) { if (toIndex > args.size()) { toIndex = args.size(); } this.jdbcTemplate.batchUpdate(sql,args.subList(fromIndex, toIndex)); fromIndex = toIndex; toIndex += BATCH_SIZE; if (toIndex > args.size()) toIndex = args.size(); } }
最主要是的是將List<bean>轉換為List<Object[]> :
private List<Object[]> transformFlowCarReportDayBoToObjects(List<FlowCarReportDayBo> flowCarReportDayBoList) { List<Object[]> list = new ArrayList<>(); Object[] object = null; for(FlowCarReportDayBo flowCarReportDayBo :flowCarReportDayBoList){ object = new Object[]{ flowCarReportDayBo.getId(), flowCarReportDayBo.getPark_number(), flowCarReportDayBo.getPark_name(), flowCarReportDayBo.getStart_time(), flowCarReportDayBo.getNature_sum_count(), flowCarReportDayBo.getTemp_car_count(), flowCarReportDayBo.getVip_car_count(), flowCarReportDayBo.getIn_car_count(), flowCarReportDayBo.getOut_car_count(), flowCarReportDayBo.getCharge_sum_count(), flowCarReportDayBo.getCharge_car_count(), flowCarReportDayBo.getFree_car_count(), flowCarReportDayBo.getDiscount_sum_count(), flowCarReportDayBo.getDiscount_local_car_count(), flowCarReportDayBo.getDiscount_bussiness_car_count(), flowCarReportDayBo.getVisit_in_car_count(), flowCarReportDayBo.getVisit_out_car_count(), flowCarReportDayBo.getBlack_in_car_count(), flowCarReportDayBo.getBlack_out_car_count(), }; list.add(object); } return list ; }