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

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. linux信号程序编译遇到的问题

    如果把这个去掉-std=c99就会运行通过 还有一点就是 for(int i=0;i<n;i++) 在循环里声明变量仅被用在c99里面.也就是要想在循环里面声明变量,就必须使用-std=c99

  2. C#操作word类文件

    最近频繁操作Word文档,写了很多word的操作代码及方法,虽然已经有很多关于word的操作类了,自己还是进行了一下整合: 1.通过模板创建新文件 2.在书签处插入值 3.插入表格 4.合并单元格 5 ...

  3. Idea配置sbt(window环境)

    近开发spark项目使用到scala语言,这里介绍如何在idea上使用sbt来编译项目. 开发环境:windows 1. 下载sbt http://www.scala-sbt.org/download ...

  4. div 背景自适应

    .bg { background: url(images/title_bg.jpg); filter: "progid:DXImageTransform.Microsoft.AlphaIma ...

  5. OC基础--常用类的初步介绍与简单实用之集合类

    集合类的异同点 一.NSArray\NSMutableArray *有序 *快速创建(只有不可变数组可以):@[obj1, obj2, obj3]; *快速访问元素:数组名[i] *只能存放对象 二. ...

  6. tp-01 搭建过程

    1:拷贝ThinkPHP框架系统文件夹自己的www目录中的tp-shop文件夹中 2:新建自己的项目文件(比如:shop)夹与ThinkPHP框架系统文件夹在同一级目录(当然也可以不同) 3: 在tp ...

  7. 多媒体开发之rtcp详解---rtcp数据包

    http://www.360doc.com/content/13/0606/10/1317564_290865866.shtml http://blog.csdn.net/hrbeuwhw/artic ...

  8. 转载:MySQL数据库INSERT、UPDATE、DELETE以及REPLACE语句的用法详解

    转自:http://www.jb51.net/article/39199.htm 本篇文章是对MySQL数据库INSERT.UPDATE.DELETE以及REPLACE语句的用法进行了详细的分析介绍, ...

  9. oracle的loop等循环语句的几个用法小例子[转]

    --loop循环用法 (输出1到10) declare v_num number(2) := 0; begin loop v_num := v_num + 1; exit when v_num > ...

  10. 对phpexcel的若干补充

    导出excel属性设置 //Include class require_once('Classes/PHPExcel.php'); require_once('Classes/PHPExcel/Wri ...