简体   繁体   中英

jdbcTemplate.batchUpdate() with smaller list than getBatchSize() throws IndexOutOfBoundsException error

I'm calling jdbcTemplate.batchUpdate() with chunks of 1000. The list can be arbitrarily large -- and sometimes it can be less than 1000, in which case there's just that one small batch. My assumption was jdbcTemplate.batchUpdate would be smart enough to figure out how many batches to execute.

But I'm seeing the following: suppose my list has 3 items:

final List<UsersT> batchInsertUsers = ...; // 3 items in List

String sqlInsert = "INSERT INTO USERS_T ...";

jdbcTemplate.batchUpdate(sqlInsert, new BatchPreparedStatementSetter() {

    @Override
    public int getBatchSize() {
        return 1000; // Max Batch size greater than current list. 1 batch expected
    }

    @Override
    public void setValues(PreparedStatement ps, int i) throws SQLException {
        ps.setInt(1, batchInsertUsers.get(i).getId()); 
        ps.setString(2, batchInsertUsers.get(i).getPassword()); 
        // etc.
    }

}

Error:

java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.get(ArrayList.java:433)
    at app.ResearcherServiceImpl$1.setValues(ResearcherServiceImpl.java:535)

int getBatchSize() Return the size of the batch.

Use this implementation :

@Override
public int getBatchSize() {
    return batchInsertUsers.size(); // Return the size of the batch.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM