Spring JdbcTemplate 批量插入操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a913858/article/details/82702034

做项目中碰到一个批量数据插入,给自己提个醒做个记录。
框架是:spring+mybatis+oracle
1.一开始我是拿SqlSessionTemplate 去操作insert mybatis用的循环list的方式。结果发现只能插入6000条,超过6000的时候会报内存溢出,具体原因也没搞清楚。(后期有机会再去看看)结果肯定是不满意的,就想到了第2种方案。
2.SqlSessionTemplate 的 batchInsert 方式结果是可以的,但是1万条数据耗时122s,时间太长了,这个客户肯定接受不了。那没有办法只能再想其他方案了。
3.最终方案:JdbcTemplate 的 batchUpdate 方式试了一下速度果然嗖嗖的。1万条数据耗时10s。
接下来上代码:

public static final int BATCH_SIZE = 5000; 
public void batchInsertJdbc(String sql, List<Object[]> batchArgs) {
		try {
			  int fromIndex = 0; int toIndex = BATCH_SIZE;
			  sql = "INSERT INTO cx_out_call_back_task ";
			  sql+=" (ID,CUST_NAME,TELEPHONE,PLATENUM,PLATECOLORTYPE,ETCCARD,CARTYPE,IDNUMBER,CARDTIME,";
			  sql+="CARDPOINT,ENDFREECONSUME,ACCOUNTBALANCE,CARDBALANCE,ORDERSOURCE,NAME_TYPE,";
			  sql+="CARDCHANNEL,CALL_TIME,TENANT_ID,source,STATE,REMARK) ";
			  sql+=" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
			  
	           	
		      while (fromIndex != batchArgs.size()) {
		        if (toIndex > batchArgs.size()) {
		          toIndex = batchArgs.size();
		        }
		        this.jdbcTemplate.batchUpdate(sql, batchArgs.subList(fromIndex, toIndex));
		        fromIndex = toIndex;
		        toIndex += BATCH_SIZE;
		        if (toIndex > batchArgs.size())
		          toIndex = batchArgs.size();
		      }
		} catch (Exception e) {
			throw new DaoException("批量插入失败", e);
		}
		
	}

猜你喜欢

转载自blog.csdn.net/a913858/article/details/82702034