JdbcTemplate的SimpleJdbcInsert支持批量插入操作。
批量插入步骤如下:
- 创建SimpleJdbcInsert对象,指定表名和JdbcTemplate:
SimpleJdbcInsert insert = new SimpleJdbcInsert(jdbcTemplate).withTableName("user");
- 设置需要插入的列名:
insert.usingColumns("name", "age");
- 构造多个参数值List,每个Map代表一条记录:
List<Map<String, Object>> batch = new ArrayList<>();
Map<String, Object> record1 = new HashMap<>();
record1.put("name", "John");
record1.put("age", 18);
batch.add(record1);
Map<String, Object> record2 = new HashMap<>();
record2.put("name", "Amy");
record2.put("age", 20);
batch.add(record2);
- 调用executeBatch()方法执行批量插入,传入parametersList:
insert.executeBatch(batch);
- SimpleJdbcInsert会自动生成如下INSERT语句,并为每个记录设置参数值:
INSERT INTO user (name, age) VALUES (?, ?)
INSERT INTO user (name, age) VALUES (?, ?)
...
一个完整示例:
SimpleJdbcInsert insert = new SimpleJdbcInsert(jdbcTemplate).withTableName("user");
insert.usingColumns("name", "age");
List<Map<String, Object>> batch = new ArrayList<>();
Map<String, Object> record1 = new HashMap<>();
record1.put("name", "John");
record1.put("age", 18);
batch.add(record1);
Map<String, Object> record2 = new HashMap<>();
record2.put("name", "Amy");
record2.put("age", 20);
batch.add(record2);
insert.executeBatch(batch);
相比单条插入,批量插入的优点是:
- 大大提高插入效率,减少数据库IO操作
- 网络开销更小
- 节省编程工作量
所以,对大量数据插入,批量插入方式是必选的,这也是SimpleJdbcInsert批量插入的意义所在。