The complement to PreparedStatementCreator is PreparedStatementSetter.
receive a PreparedStatement and are responsible for setting any of the parameters.
Since many updates consist of creating a PreparedStatement from a SQL string and then binding parameters, JdbcTemplate provides an execute(String sql,Object[] params) method that facilitates just that.
String sql = "insert into person (id, firstName, lastName) " + "values (?, ?, ?)";
Object[] params = new Object[] { person.getId(),person.getFirstName(),person.getLastName() };
return jdbcTemplate.update(sql, params);
Behind the scenes, the JdbcTemplate class creates a PreparedStatementCreator and PreparedStatementSetter. But now we don’t have to worry about that. We just supply the SQL and the parameters.
One improvement we can make is to use the JdbcTemplate method that also accepts the JDBC types of our parameters, update(String sql, Object[] args, int[] argTypes). This provides type safety,
getBatchSize() tells the JdbcTemplate class how many statements to create.This also determines how many times setValues() will be called.
public int[] updatePersons(final List persons) {
String sql = "insert into person (id, firstName, lastName) " + "values (?, ?, ?)";
BatchPreparedStatementSetter setter = null;
setter = new BatchPreparedStatementSetter() {
public int getBatchSize() {
return persons.size();
}
public void setValues(PreparedStatement ps, int index)
throws SQLException {
Person person = (Person) persons.get(index);
ps.setInt(0, person.getId().intValue());
ps.setString(1, person.getFirstName());
ps.setString(2, person.getLastName());
}
};
return jdbcTemplate.batchUpdate(sql, setter);
}
So if your JDBC driver supports batching, the updates will be batched, creating more efficient database access. If not, Spring will simulate batching, but the statements will be executed individually.
Reading data:
Instead, we simply need to tell Spring what to do with each row in the ResultSet. We do so through the RowCallbackHandler interface by implementing its only method:
void processRow(java.sql.ResultSet rs)
public Person getPerson(final Integer id) {
String sql = "select id, first_name, last_name from person " + "where id = ?";
final Person person = new Person();
final Object[] params = new Object[] { id };
jdbcTemplate.query(sql, params, new RowCallbackHandler(){
public void processRow(ResultSet rs) throws SQLException {
person.setId(new Integer(rs.getInt("id")));
person.setFirstName(rs.getString("first_name"));
person.setLastName(rs.getString("last_name"));
}
});
return person;
}