spring jdbcTemplate 批量插入 大量数据 到数据库

  public void insertBANDWIDTH_AREA_TEMP(final List<AreaTempBandwidth> bands) {
        long executeStart = System.currentTimeMillis();
        DefaultTransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(paramTransactionDefinition);
        logger.info("start to insertBANDWIDTH_AREA_TEMP ......");
        try {
            jdbcTemplate
                    .batchUpdate(
                            "insert INTO BANDWIDTH_AREA_TEMP(TIME_NUM,CHANNEL_ID,AREA_ID,IN_DATA,OUT_DATA,DAY) values(?,?,?,?,?,?)",
                            new BatchPreparedStatementSetter() {

                                @Override
                                public void setValues(PreparedStatement ps, int i) throws SQLException {
                                    // TODO Auto-generated method stub
                                    ps.setString(1, bands.get(i).getTimeNum());
                                    ps.setString(2, bands.get(i).getChannelID());
                                    ps.setString(3, bands.get(i).getAreaID());
                                    ps.setString(4, bands.get(i).getInData());
                                    ps.setString(5, bands.get(i).getOutData());
                                    ps.setString(6, bands.get(i).getDay());
                                    //每50000条进行事物提交,不加的话数据量超过6w会有问题
                                    if (i % 50000 == 0) {
                                        ps.executeBatch(); //执行prepareStatement对象中所有的sql语句  
                                    }
                                }

                                @Override
                                public int getBatchSize() {
                                    // TODO Auto-generated method stub
                                    return bands.size();
                                }
                            });
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
        } finally {
            bands.clear();
        }

        logger.info("insertBANDWIDTH_AREA_TEMP  finished use [" + (System.currentTimeMillis() - executeStart) / 1000
                + "] seconds");
    }

你可能感兴趣的:(JdbcTemplate)