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

后端 未结 8 2386
终归单人心
终归单人心 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 19:02

    Change your sql insert to INSERT INTO TABLE(x, y, i) VALUES(1,2,3). The framework creates a loop for you. For example:

    public void insertBatch(final List customers){
    
      String sql = "INSERT INTO CUSTOMER " +
        "(CUST_ID, NAME, AGE) VALUES (?, ?, ?)";
    
      getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() {
    
        @Override
        public void setValues(PreparedStatement ps, int i) throws SQLException {
            Customer customer = customers.get(i);
            ps.setLong(1, customer.getCustId());
            ps.setString(2, customer.getName());
            ps.setInt(3, customer.getAge() );
        }
    
        @Override
        public int getBatchSize() {
            return customers.size();
        }
      });
    }
    

    IF you have something like this. Spring will do something like:

    for(int i = 0; i < getBatchSize(); i++){
       execute the prepared statement with the parameters for the current iteration
    }
    

    The framework first creates PreparedStatement from the query (the sql variable) then the setValues method is called and the statement is executed. that is repeated as much times as you specify in the getBatchSize() method. So the right way to write the insert statement is with only one values clause. You can take a look at http://docs.spring.io/spring/docs/3.0.x/reference/jdbc.html

提交回复
热议问题