TIP: Batch Updates with Spring JdcbTemplate

Wednesday, October 23, 2019 Labels: , , , , ,
Spring JdbcTemplate offers the following method to do multiple updates.

int[] org.springframework.jdbc.core.JdbcTemplate.batchUpdate(String sql, BatchPreparedStatementSetter pss) throws DataAccessException

1. Issue multiple update statements on a single PreparedStatement, using batch updates and a BatchPreparedStatementSetter to set values.
2. Will fall back to separate updates on a single PreparedStatement if the JDBC driver does not support batch updates.

Specified by: batchUpdate(...) in JdbcOperations
sql defining PreparedStatement that will be reused. All statements in the batch will use the same SQL.
pss object to set parameters on the PreparedStatement created by this method
an array of the number of rows affected by each statement
DataAccessException - if there is any problem issuing the update

Here is a reference code, where jdbcTemplate is already @Autowired.

public int[] insertPersons(List persons) {
    return jdbcTemplate.batchUpdate(
        "insert into staging.storage_insight_call_detail(first_name, middle_name, last_name) values(?, ?, ?)",
        new BatchPreparedStatementSetter() {

          public void setValues(PreparedStatement ps, int i) throws SQLException {
            ps.setString(1, persons.get(i).firstName());
            ps.setString(2, persons.get(i).middleName());
            ps.setString(3, persons.get(i).lastName());
          public int getBatchSize() {
            return persons.size();



Post a Comment

Waqas Sadiq © 2014