1. As we know, it is meaningless to execute batch query.
There is only batchUpdate provided in JdbcTemplate.
/** * @param sql defining an array of SQL statements that will be executed. */ public int[] batchUpdate(final String[] sql); /** * @param sql defining PreparedStatement that will be reused. * @param pss object to set parameters on the PreparedStatement */ public int[] batchUpdate(String sql, final BatchPreparedStatementSetter pss); /** * @param sql the SQL statement to execute * @param batchArgs the List of Object arrays containing the batch of arguments for the query */ public int[] batchUpdate(String sql, List<Object[]> batchArgs); /** * @param sql the SQL statement to execute. * @param batchArgs the List of Object arrays containing the batch of arguments for the query * @param argTypes SQL types of the arguments */ public int[] batchUpdate(String sql, List<Object[]> batchArgs, int[] argTypes); /** * @param sql the SQL statement to execute. * @param batchArgs the List of Object arrays containing the batch of arguments for the query * @param batchSize batch size * @param pss ParameterizedPreparedStatementSetter to use */ public <T> int[][] batchUpdate(String sql, final Collection<T> batchArgs, final int batchSize, final ParameterizedPreparedStatementSetter<T> pss);
Example:
package edu.xmu.jdbc.dao; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter; import org.springframework.jdbc.core.support.JdbcDaoSupport; import edu.xmu.jdbc.bean.Student; public class BatchDao extends JdbcDaoSupport { public int[] batchExecution() { JdbcTemplate jdbcTemplate = getJdbcTemplate(); String sql = "update student set name='aaa' where id=1"; String sql2 = "update student set name='bbb' where id=2"; String sql3 = "update student set name='ccc' where id=3"; final String[] sqls = new String[] { sql, sql2, sql3 }; return jdbcTemplate.batchUpdate(sqls); } public int[] batchCreate(final List<Student> studentList) { JdbcTemplate jdbcTemplate = getJdbcTemplate(); String sql = "insert into student(name, age) values(?, ?)"; int[] updateCounts = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) throws SQLException { Student student = studentList.get(i); ps.setString(1, student.getName()); ps.setInt(2, student.getAge()); } public int getBatchSize() { return studentList.size(); } }); return updateCounts; } public int[] batchCreate2(final List<Student> studentList) { JdbcTemplate jdbcTemplate = getJdbcTemplate(); String sql = "insert into student(name, age) values(?, ?)"; List<Object[]> batchArgs = new ArrayList<Object[]>(); for (Student student : studentList) { String name = student.getName(); int age = student.getAge(); Object[] objects = new Object[] { name, age }; batchArgs.add(objects); } return jdbcTemplate.batchUpdate(sql, batchArgs); } public int[] batchCreate3(final List<Student> studentList) { JdbcTemplate jdbcTemplate = getJdbcTemplate(); String sql = "insert into student(name, age) values(?, ?)"; List<Object[]> batchArgs = new ArrayList<Object[]>(); for (Student student : studentList) { String name = student.getName(); int age = student.getAge(); Object[] objects = new Object[] { name, age }; batchArgs.add(objects); } return jdbcTemplate.batchUpdate(sql, batchArgs, new int[] { java.sql.Types.VARCHAR, java.sql.Types.INTEGER }); } public int[][] batchCreate4(final List<Student> studentList) { JdbcTemplate jdbcTemplate = getJdbcTemplate(); String sql = "insert into student(name, age) values(?, ?)"; List<Object[]> batchArgs = new ArrayList<Object[]>(); for (Student student : studentList) { String name = student.getName(); int age = student.getAge(); Object[] objects = new Object[] { name, age }; batchArgs.add(objects); } return jdbcTemplate.batchUpdate(sql, studentList, studentList.size(), new ParameterizedPreparedStatementSetter<Student>() { public void setValues(PreparedStatement ps, Student student) throws SQLException { ps.setString(1, student.getName()); ps.setInt(2, student.getAge()); } }); } }
package edu.xmu.jdbc.dao; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; import edu.xmu.jdbc.bean.Student; public class BatchDaoTest { private DriverManagerDataSource dataSource; private String url = "jdbc:mysql://localhost:3306/jdbctest"; private String username = "root"; private String password = "root"; private BatchDao dao; @Before public void setUp() { dataSource = new DriverManagerDataSource(url, username, password); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dao = new BatchDao(); dao.setDataSource(dataSource); } @Test public void batchCreateTest() { List<Student> studentList = new ArrayList<Student>(); Student student = new Student("Davy", 24); studentList.add(student); student = new Student("Jones", 25); studentList.add(student); int[] rowCounts = dao.batchCreate(studentList); System.out.println("start batchCreateTest"); for (int i : rowCounts) { System.out.println(i + " row affected."); } System.out.println("======================"); } @Test public void batchCreate2Test() { List<Student> studentList = new ArrayList<Student>(); Student student = new Student("Davy", 24); studentList.add(student); student = new Student("Jones", 25); studentList.add(student); int[] rowCounts = dao.batchCreate2(studentList); System.out.println("start batchCreate2Test"); for (int i : rowCounts) { System.out.println(i + " row affected."); } System.out.println("======================"); } @Test public void batchCreate3Test() { List<Student> studentList = new ArrayList<Student>(); Student student = new Student("Davy", 24); studentList.add(student); student = new Student("Jones", 25); studentList.add(student); int[] rowCounts = dao.batchCreate3(studentList); System.out.println("start batchCreate3Test"); for (int i : rowCounts) { System.out.println(i + " row affected."); } System.out.println("======================"); } @Test public void batchCreate4Test() { List<Student> studentList = new ArrayList<Student>(); Student student = new Student("Davy", 24); studentList.add(student); student = new Student("Jones", 25); studentList.add(student); int[][] rowCounts = dao.batchCreate4(studentList); System.out.println("start batchCreateTest"); for (int i = 0; i < rowCounts.length; i++) { int[] list = rowCounts[i]; for (int j = 0; j < list.length; j++) { int count = list[j]; System.out.println("Batch " + i + " execute. " + count + " row affected."); } } System.out.println("======================"); } @After public void tearDown() { } }
Comments:
Still have some question about the ParameterizedPreparedStatementSetter approach.
Why it will return int[][] instead of int[]?
2. SimpleJdbcTemplate provided an additional approach for batchUpdate
public int[] batchUpdate(String sql, SqlParameterSource[] batchArgs);
As we can see, we can pass a list of SqlParameterSource as batch parameters.
And now since SimpleJdbcTemplate is depreciated, we still can not find alternative method in JdbcTemplate.
And why?
package edu.xmu.jdbc.dao; import java.util.List; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils; import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; import edu.xmu.jdbc.bean.Student; @SuppressWarnings("deprecation") public class SimpleBatchDao extends SimpleJdbcDaoSupport { public int[] batchCreate(List<Student> studentList) { String sql = "insert into student(name, age) values(:name, :age)"; SimpleJdbcTemplate simpleJdbcTemplate = getSimpleJdbcTemplate(); SqlParameterSource[] paramSources = SqlParameterSourceUtils .createBatch(studentList.toArray()); return simpleJdbcTemplate.batchUpdate(sql, paramSources); } }
package edu.xmu.jdbc.dao; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; import edu.xmu.jdbc.bean.Student; public class SimpleBatchDaoTest { private DriverManagerDataSource dataSource; private String url = "jdbc:mysql://localhost:3306/jdbctest"; private String username = "root"; private String password = "root"; private SimpleBatchDao dao; @Before public void setUp() { dataSource = new DriverManagerDataSource(url, username, password); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dao = new SimpleBatchDao(); dao.setDataSource(dataSource); } @Test public void batchCreateTest() { List<Student> studentList = new ArrayList<Student>(); Student student = new Student("Davy", 24); studentList.add(student); student = new Student("Jones", 25); studentList.add(student); int[] rowCounts = dao.batchCreate(studentList); System.out.println("start batchCreateTest"); for (int i : rowCounts) { System.out.println(i + " row affected."); } System.out.println("======================"); } @After public void tearDown() { } }
3. BatchUpdate and auto-generated keys.
Still, we may wonder that how can we get the auto-generated keys when execute batchUpdate?
Sadly, there is no provided solution for this.<See ref-link-2>
Reference Links:
2) http://stackoverflow.com/questions/6272272/batchsqlupdate-how-to-get-auto-generated-keys testify that there is no auto-generated key fetching solution. Also, it offers a good solution solving this.
相关推荐
1. **JdbcTemplate**:这是Spring JDBC的核心类,它通过模板方法模式将常见的JDBC操作进行了封装,如执行SQL查询、更新、调用存储过程等。开发者只需要关注SQL语句和参数,而无需处理连接创建、关闭、异常处理等繁琐...
1. **JdbcTemplate**:这是Spring JDBC的基础组件,它通过模板方法模式封装了常见的JDBC操作,如执行SQL查询、更新、存储过程等。使用JdbcTemplate,开发者无需手动管理数据库连接、预编译语句、结果集转换等细节,...
Spring JDBC通过提供JdbcTemplate和SimpleJdbcTemplate等工具类,帮助开发者以更安全、更易于管理的方式与数据库进行交互,降低了传统JDBC代码的复杂性。下面我们将详细探讨Spring JDBC的核心概念、工作原理以及如何...
Spring Data JDBC与JDBC是两种不同的数据库访问方式,它们在Java开发中有着广泛的应用。JDBC(Java Database Connectivity)是Java平台的标准API,用于与各种数据库进行交互。它提供了低级别的数据库操作,如建立...
本篇将深入探讨Spring JDBC的核心概念、使用方法以及它如何通过JdbcTemplate对象简化JDBC的开发。 首先,让我们了解Spring JDBC的基本理念。Spring JDBC的目标是减少传统JDBC代码的复杂性和易错性,通过提供一套...
Spring JDBC是Spring框架的一个核心模块,它为Java数据库连接(JDBC)提供了一种抽象层,使得开发者可以更轻松地处理数据库操作。Spring JDBC模块的主要目标是减少对JDBC API的直接依赖,通过提供一种更加高级、易于...
Spring JDBC模板类——`org.springframework.jdbc.core.JdbcTemplate`是Spring框架中的核心组件,它为Java开发者提供了一种方便、安全的方式来执行SQL语句,而无需直接管理数据库连接。`JdbcTemplate`通过抽象出低...
Spring JdbcTemplate的出现是为了弥补原生JDBC在编码上的繁琐,它通过模板方法模式,将SQL执行、结果集处理等进行了抽象,使得开发者可以更专注于业务逻辑,而无需过多关注数据库访问的细节。同时,它还提供了事务...
Spring Boot JDBC是Spring框架的一个重要组成部分,它简化了在Java应用程序中使用JDBC(Java Database Connectivity)进行数据库操作的方式。Spring Boot的设计理念是“约定优于配置”,因此它为开发者提供了开箱即...
Spring JDBCTemplate是一个强大的工具,它是Spring框架的一部分,用于简化Java数据库连接(JDBC)操作。在本示例中,我们将深入探讨Spring JDBCTemplate的工作原理、优势以及如何在实际项目中进行配置和使用。 首先...
`spring-jdbc-4.2.xsd`是Spring 4.2版本的JDBC配置XML Schema定义,它定义了一系列元素和属性,用来描述如何配置Spring的JdbcTemplate、NamedParameterJdbcTemplate、SimpleJdbcInsert等核心组件,以及事务管理相关...
在本实例中,我们将深入探讨Spring JDBC的使用,并以`SpringJdbcTemplate`为例来阐述其主要功能和优势。 首先,Spring JDBC通过`JdbcTemplate`和`NamedParameterJdbcTemplate`类提供了强大的数据库访问功能。`...
Spring JDBC 提供了 JdbcTemplate 和 NamedParameterJdbcTemplate,这两个工具类极大地减少了我们处理数据库连接、事务管理、结果集映射等工作所需的手动编码。 首先,集成Spring JDBC需要引入相应的jar包。在现代...
JdbcTemplate是Spring JDBC模块中的核心组件,它提供了一种模板化的JDBC操作方式,降低了数据库访问的复杂性,同时保持了良好的封装和异常处理机制。在使用Spring JDBC之前,我们需要确保引入了必要的jar包。这里...
Spring JDBC简化了数据库操作,例如,通过`JdbcTemplate`可以方便地执行SQL语句,进行增删改查操作。同时,Spring的事务管理功能(`PlatformTransactionManager`)可以确保在多条数据库操作之间保持事务的原子性。在...
基于spring jdbc的上层封装,底层jdbc操作基于JdbcTemplate,支持MySql、SqlServer、Oracle数据库,强弱类型完美结合 1、mini-jdbc:针对spring jdbc的一些不方便的地方,做了一些封装,大小写不敏感,简化了日常的...
标题 "jdbcTemplate-spring对jdbc的支持" 涉及到的是Spring框架中的一个核心组件——JdbcTemplate,它是Spring对Java数据库连接(JDBC)的一种封装,用于简化数据库操作。JdbcTemplate提供了一种模板方法模式,使得...
- 对于批量插入或更新,Spring JDBC提供了`batchUpdate()`方法,可以有效地提高性能。 5. **异常处理**: - Spring JDBC将JDBC的异常转换为Spring的`DataAccessException`家族,使得异常处理更加统一和简单。 6....
JdbcTemplate是Spring框架提供的一种用于简化JDBC编程的对象。通过封装原生的JDBC API,JdbcTemplate不仅提高了代码的可读性和可维护性,还帮助开发者避免了许多常见的错误,比如资源关闭、SQL注入等问题。 Spring...
Spring JDBC是Spring框架的一部分,它提供了一种抽象层,使得我们能够更方便地使用Java数据库连接(JDBC)技术。这个“SpringJDBC.rar”压缩包文件可能包含了关于如何在Spring框架中集成和使用JDBC的相关示例和教程...