Why Spring's jdbcTemplate.batchUpdate() so slow?

后端 未结 8 2363
终归单人心
终归单人心 2020-12-04 18:11

I\'m trying to find the faster way to do batch insert.

I tried to insert several batches with jdbcTemplate.update(String sql), wher

8条回答
  •  自闭症患者
    2020-12-04 18:54

    Solution given by @Rakesh worked for me. Significant improvement in performance. Earlier time was 8 min, with this solution taking less than 2 min.

    DataSource ds = jdbcTemplate.getDataSource();
    Connection connection = ds.getConnection();
    connection.setAutoCommit(false);
    String sql = "insert into employee (name, city, phone) values (?, ?, ?)";
    PreparedStatement ps = connection.prepareStatement(sql);
    final int batchSize = 1000;
    int count = 0;
    
    for (Employee employee: employees) {
    
        ps.setString(1, employee.getName());
        ps.setString(2, employee.getCity());
        ps.setString(3, employee.getPhone());
        ps.addBatch();
    
        ++count;
    
        if(count % batchSize == 0 || count == employees.size()) {
            ps.executeBatch();
            ps.clearBatch(); 
        }
    }
    
    connection.commit();
    ps.close();
    

提交回复
热议问题