日期:2014-05-16  浏览次数:20487 次

SimpleJdbcTemplate batchUpdate 推荐使用方式

??? SimpleJdbcTemplate 类提供了另外一种批量操作的方式。无需实现一个特定的接口,你只需要提供所有在调用过程 中要用到的参数,框架会遍历这些参数值,并使用内置的prepared statement类进行批量操作。API将根据你是否使用命名参数而有所不同。对于使用命名参数的情况,你需要提供一个SqlParameterSource 的数组, 其中的每个元素将将作为批量操作的参数。 你可以使用SqlParameterSource.createBatch 方法,通过传入一个JavaBean的数组或者一个包含了参数键值对的Map数组来创建这个数组。
????? 下面的示例展示了使用命名参数进行批量更新的方法:

?

public class JdbcActorDao implements ActorDao {
    private SimpleJdbcTemplate simpleJdbcTemplate;
    public void setDataSource(DataSource dataSource) {
        this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
    }
    public int[] batchUpdate(final List<Actor> actors) {
        SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(actors.toArray());
        int[] updateCounts = simpleJdbcTemplate.batchUpdate(
                "update t_actor set first_name = :firstName, last_name = :lastName where id = :id",
                batch);
        return updateCounts;
    }
    //  ... additional methods
}
?