读书人

SimpleJdbcTemplate batchUpdate 推荐

发布时间: 2012-09-06 10:37:01 作者: rapoo

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}
?

读书人网 >其他数据库

热点推荐