public void addBatchScyh(List<User> userList) throws Exception {
final List<User> yhList = userList;
final Long drsj = CalendarUtil.getLongDateTime();
if(yhList != null && yhList.size() > 0){
this.getJdbcTemplate().batchUpdate("insert into user (id,yhbh,yhxm,lxfs,bbtnz,xtxjd,drsj,drpc,yhbz) VALUES (SEQ_USER_ID.nextval,?, ?, ?, ?, ? ,? ,? ,?)", new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
User user = yhList.get(i);
ps.setBigDecimal(1, BigDecimal.valueOf(Long.decode(user.getYhbh())));
ps.setString(2, user.getYhxm());
ps.setLong(3, Long.decode(user.getLxfs()));
ps.setString(4, user.getBbtnz());
ps.setString(5, user.getXtxjd());
ps.setLong(6, drsj);
ps.setBigDecimal(7, BigDecimal.valueOf(Long.decode(user.getDrpc())));
ps.setString(8, "1");
//每2000条进行事物提交
if (i%2000 == 0) {
ps.executeBatch(); //执行prepareStatement对象中所有的sql语句
getSession().flush();//数据库与缓存同步
getSession().clear();//清空缓存
}
}
@Override
public int getBatchSize() {
return yhList.size();
}
});
}
}
工作的过程中遇到了一个要海量插入数据的问题,在网上查了很多资料,归纳起来,最快,效率最高的方法当然是采用,JDBC了,但是系统采用的是SSH的架构,退而求其次选择Spring中的JDBCTemplate批量插入操作,其中,每2000条数据提交一次并使session与缓存同步,这样的操作,我也是“小马过河”试一试,但实际的运行结果,表明,确实提高了效率,5万条数据的导入时间大概为40s左右,还行吧,反正是满足领导的要求了,嘿嘿~~