这里主要是看的官方文档,如何翻译:

NamedParameterJdbcTemplate

The NamedParameterJdbcTemplate class adds support for programming JDBC statements using named parameters, as opposed to programming JDBC statements using only classic placeholder ( '?') arguments. The NamedParameterJdbcTemplate class wraps aJdbcTemplate, and delegates to the wrapped JdbcTemplate to do much of its work. This section describes only those areas of the NamedParameterJdbcTemplate class that differ from the JdbcTemplate itself; namely, programming JDBC statements using named parameters.

// some JDBC-backed DAO class...
private NamedParameterJdbcTemplate namedParameterJdbcTemplate; public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
} public int countOfActorsByFirstName(String firstName) { String sql = "select count(*) from T_ACTOR where first_name = :first_name"; SqlParameterSource namedParameters = new MapSqlParameterSource("first_name", firstName); return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);
}

Notice the use of the named parameter notation in the value assigned to the sql variable, and the corresponding value that is plugged into the namedParameters variable (of type MapSqlParameterSource).

Alternatively, you can pass along named parameters and their corresponding values to a NamedParameterJdbcTemplate instance by using the Map-based style.The remaining methods exposed by the NamedParameterJdbcOperations and implemented by theNamedParameterJdbcTemplate class follow a similar pattern and are not covered here.

The following example shows the use of the Map-based style.

private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

public void setDataSource(DataSource dataSource) {
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
} public int countOfActorsByFirstName(String firstName) { String sql = "select count(*) from T_ACTOR where first_name = :first_name"; Map<String, String> namedParameters = Collections.singletonMap("first_name", firstName); return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);
}

Basic batch operations with the JdbcTemplate

You accomplish JdbcTemplate batch processing by implementing two methods of a special interface, BatchPreparedStatementSetter, and passing that in as the second parameter in your batchUpdate method call. Use the getBatchSize method to provide the size of the current batch. Use the setValues method to set the values for the parameters of the prepared statement. This method will be called the number of times that you specified in the getBatchSize call. The following example updates the actor table based on entries in a list. The entire list is used as the batch in this example:

public class JdbcActorDao implements ActorDao {
private JdbcTemplate jdbcTemplate; public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
} public int[] batchUpdate(final List<Actor> actors) {
int[] updateCounts = jdbcTemplate.batchUpdate("update t_actor set first_name = ?, " +
"last_name = ? where id = ?",
new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, actors.get(i).getFirstName());
ps.setString(2, actors.get(i).getLastName());
ps.setLong(3, actors.get(i).getId().longValue());
} public int getBatchSize() {
return actors.size();
}
});
return updateCounts;
} // ... additional methods
}

If you are processing a stream of updates or reading from a file, then you might have a preferred batch size, but the last batch might not have that number of entries. In this case you can use the InterruptibleBatchPreparedStatementSetter interface, which allows you to interrupt a batch once the input source is exhausted. The isBatchExhausted method allows you to signal the end of the batch.

Batch operations with a List of objects

Both the JdbcTemplate and the NamedParameterJdbcTemplate provides an alternate way of providing the batch update. Instead of implementing a special batch interface, you provide all parameter values in the call as a list. The framework loops over these values and uses an internal prepared statement setter. The API varies depending on whether you use named parameters. For the named parameters you provide an array of SqlParameterSource, one entry for each member of the batch. You can use theSqlParameterSource.createBatch method to create this array, passing in either an array of JavaBeans or an array of Maps containing the parameter values.

This example shows a batch update using named parameters:

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

For an SQL statement using the classic "?" placeholders, you pass in a list containing an object array with the update values. This object array must have one entry for each placeholder in the SQL statement, and they must be in the same order as they are defined in the SQL statement.

The same example using classic JDBC "?" placeholders:

public class JdbcActorDao implements ActorDao {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
} public int[] batchUpdate(final List<Actor> actors) {
List<Object[]> batch = new ArrayList<Object[]>();
for (Actor actor : actors) {
Object[] values = new Object[] {
actor.getFirstName(),
actor.getLastName(),
actor.getId()};
batch.add(values);
}
int[] updateCounts = jdbcTemplate.batchUpdate(
"update t_actor set first_name = ?, last_name = ? where id = ?",
batch);
return updateCounts;
} // ... additional methods }

All of the above batch update methods return an int array containing the number of affected rows for each batch entry. This count is reported by the JDBC driver. If the count is not available, the JDBC driver returns a -2 value.

Batch operations with multiple batches

The last example of a batch update deals with batches that are so large that you want to break them up into several smaller batches. You can of course do this with the methods mentioned above by making multiple calls to the batchUpdate method, but there is now a more convenient method. This method takes, in addition to the SQL statement, a Collection of objects containing the parameters, the number of updates to make for each batch and a ParameterizedPreparedStatementSetter to set the values for the parameters of the prepared statement. The framework loops over the provided values and breaks the update calls into batches of the size specified.

This example shows a batch update using a batch size of 100:

public class JdbcActorDao implements ActorDao {

    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
} public int[][] batchUpdate(final Collection<Actor> actors) {
int[][] updateCounts = jdbcTemplate.batchUpdate(
"update t_actor set first_name = ?, last_name = ? where id = ?",
actors,
100,
new ParameterizedPreparedStatementSetter<Actor>() {
public void setValues(PreparedStatement ps, Actor argument) throws SQLException {
ps.setString(1, argument.getFirstName());
ps.setString(2, argument.getLastName());
ps.setLong(3, argument.getId().longValue());
}
});
return updateCounts;
} // ... additional methods }

The batch update methods for this call returns an array of int arrays containing an array entry for each batch with an array of the number of affected rows for each update. The top level array’s length indicates the number of batches executed and the second level array’s length indicates the number of updates in that batch. The number of updates in each batch should be the batch size provided for all batches except for the last one that might be less, depending on the total number of update objects provided. The update count for each update statement is the one reported by the JDBC driver. If the count is not available, the JDBC driver returns a -2 value.

springjdbc的批量操作的更多相关文章

  1. 【Hibernate框架】批量操作Batch总结

    在我们做.net系统的时候,所做的最常见的批量操作就是批量导入.插入.更新.删除等等,以前我们怎么做呢?基本上有以下几种方式: 1.利用循环调用insert方法,一条条插入. public boole ...

  2. Spring-JDBC实现Contact的CRUD

    Spring-JDBC完成Contact的CRUD. 两点注意: 1.log4j.properties文件不能少 2.注意导入的包之间的依赖关系以及版本要求. 项目结构: 主要文件: 建表脚本: CR ...

  3. sql传入组合字符串批量操作

    批量操作时我们可以传入一个有规律的ID或则是其他唯一值字段的组合字符串,然后:select/update/inset......where  字段 in(传入的组合字符串),而且很多时候我们还涉及到其 ...

  4. SpringJDBC解析4-query方法

    重要步骤说明: 首先是从PersonServiceImpl方法进去,调用JdbcTemplate的query方法,然后执行一连串错中复杂的调用,而且里面有很多函数都是以回调形式处理, 1)JdbcTe ...

  5. SpringJDBC解析1-使用示例

    JDBC(Java Data Base Connectivity,Java数据库连接)是一种用于执行SQL语句的JavaAPI,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组 ...

  6. MyBatis的几种批量操作

    MyBatis中批量插入 方法一: <insert id="insertbatch" parameterType="java.util.List"> ...

  7. ibatis批量操作补充

    ibatis批量操作  这文章的补充吧. review代码的时候发现一个页面应用排序设置功能,原先代码中,进行了循环update实现.虽然应用较少,不过无谓浪费数据库链接实在不是一个好的想法. 所以, ...

  8. Magicodes.WeiChat——ASP.NET Scaffolding生成增删改查、分页、搜索、删除确认、批量操作、批量删除等业务代码

    关于T4代码生成这块,我之前写过几篇帖子,如:<Magicodes.NET框架之路——让代码再飞一会(ASP.NET Scaffolding)>(http://www.cnblogs.co ...

  9. springJDBC学习笔记和实例

    前言:相对于Mybatis(ibatis),个人感觉springJDBC更灵活,主要实现类JdbcTemplate:它替我们完成了资源的创建以及释放工作,从而简化了我们对JDBC的使用.它还可以帮助我 ...

随机推荐

  1. AX88772B 驱动移植

    Linux kernel 3.2.0 捏自带的AX88772B 不稳定,现用 AX88772B 官方的驱动进行移植测试. 驱动下载地址: http://www.asix.com.tw/cs/produ ...

  2. [pthread]Linux C 多线程简单示例

    #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void ...

  3. BeamNG.drive物理引擎评鉴

    BeamNG.drive是一款由BeamNG公司开发并于2013年首次发布的软体物理模拟游戏.作为模拟游戏,特别是物理模拟的粉丝,我早早就开始使用BeamNG.drive.我立即对崩溃的准确性和细节印 ...

  4. 1​1​.​0​5​9​2​M​晶​振​与12M晶振

    标准的51单片机晶振是1.2M-12M,一般由于一个机器周期是12个时钟周期,所以先12M时,一个机器周期是1US,好计算,而且速度相对是最高的(当然现在也有更高频率的单片机). 11.0592M是因 ...

  5. ajax回调函数中使用$(this)取不到对象的解决方法

    如果在ajax的回调函数内使用$(this)的话,实践证明,是取不到任何对象的,需要的朋友可以参考下 $(".derek").each(function(){ $(this).cl ...

  6. GOF23设计模式汇总

    转自:http://www.cnblogs.com/zhili/p/DesignPatternSummery.html#3037698 C#设计模式总结 一.引言 经过这段时间对设计模式的学习,自己的 ...

  7. Latex的各种帽子

    \hat{A} \widehat{A} \tilde{A} \widetilde{A} \overline{A} \underline{A} \overbrace{A} \underbrace{A} ...

  8. Apache -- phpmyadmin导入文件过大

    方法一: 找到php.ini(或php.ini-pre1.7.2)搜索这3个地方: upload_max_filesize memory_limit post_max_size 将他们后面的值修改成大 ...

  9. linux下安装dovecot

    Dovecot是一个开源的,为Linux/Unix-like系统提供IMAP,POP3服务的软件.主要是为了安全产生的,不管大小应用,Dovecot都是一个非常优秀的选择.它非常快,配置简单,不需要专 ...

  10. js上传本地图片遇到的问题

    1.改变页面文件上传默认的样式 <input type="text" size="20" id="upfile" style=&quo ...