JdbcTemplate also provides convenient methods to execute batch operations.
Batch Insert
final ArrayList<Student> list = // Get list of students to insert..
String sql = "insert into student (id, f_name, l_name, age, address) VALUES (?, ?, ?, ?, ?)"
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Student s = l.get(i);
ps.setString(1, s.getId());
ps.setString(2, s.getF_name());
ps.setString(3, s.getL_name());
ps.setInt(4, s.getAge());
ps.setString(5, s.getAddress());
}
@Override
public int getBatchSize() {
return l.size();
}
});
Batch Update
final ArrayList<Student> list = // Get list of students to update..
String sql = "update student set f_name = ?, l_name = ?, age = ?, address = ? where id = ?"
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Student s = l.get(i);
ps.setString(1, s.getF_name());
ps.setString(2, s.getL_name());
ps.setInt(3, s.getAge());
ps.setString(4, s.getAddress());
ps.setString(5, s.getId());
}
@Override
public int getBatchSize() {
return l.size();
}
});
There are further batchUpdate methods which accept List of object array as input parameters. These methods internally use BatchPreparedStatementSetter to set the values from the list of arrays into sql statement.