批量操作
JdbcTemplate 还提供了执行批处理操作的便捷方法。
批量插入
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();
}
});
批量更新
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();
}
});
还有一些 batchUpdate 方法接受对象数组列表作为输入参数。这些方法在内部使用 BatchPreparedStatementSetter 将数组列表中的值设置为 sql 语句。