“JdbcTemplate 批量操作”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) (建立内容为“1”的新页面) |
Jihongchang(讨论 | 贡献) |
||
第1行: | 第1行: | ||
− | 1 | + | 数据库脚本<syntaxhighlight lang="sql"> |
+ | CREATE TABLE `new_table` ( | ||
+ | `id` int(11) NOT NULL AUTO_INCREMENT, | ||
+ | `age` int(11) DEFAULT NULL, | ||
+ | `name` varchar(45) COLLATE utf8mb4_bin DEFAULT NULL, | ||
+ | PRIMARY KEY (`id`) | ||
+ | ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; | ||
+ | |||
+ | </syntaxhighlight>测试代码<syntaxhighlight lang="java"> | ||
+ | @SpringBootTest(classes = HdDemo001Application.class) | ||
+ | public class JdbcTemplateTest { | ||
+ | |||
+ | @Autowired | ||
+ | JdbcTemplate jdbcTemplate; | ||
+ | |||
+ | @Test | ||
+ | public void testInsert() { | ||
+ | String sql = "insert into new_table(age, name) values (?, ?)"; | ||
+ | |||
+ | List<Student> studentList = new ArrayList<>(); | ||
+ | |||
+ | for (int i = 0; i < 100; i++) { | ||
+ | Student student = new Student(); | ||
+ | student.setAge(18); | ||
+ | student.setName("你好"); | ||
+ | studentList.add(student); | ||
+ | } | ||
+ | |||
+ | |||
+ | int[][] array = jdbcTemplate.batchUpdate(sql, studentList, 10, new InsertStudentSetter()); | ||
+ | |||
+ | System.out.println(JSON.toJSONString(array)); | ||
+ | |||
+ | |||
+ | } | ||
+ | |||
+ | } | ||
+ | </syntaxhighlight>输出结果:<syntaxhighlight lang="console"> | ||
+ | [[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1]] | ||
+ | </syntaxhighlight>studentList 是全量数据,studentList 后面的 int 参数是每一批次执行多少个语句,所以返回二维数组,最里面数组的数字是 insert 或者 update 语句的受影响行数。 |
2025年6月7日 (六) 09:42的最新版本
数据库脚本
CREATE TABLE `new_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) DEFAULT NULL,
`name` varchar(45) COLLATE utf8mb4_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
测试代码
@SpringBootTest(classes = HdDemo001Application.class)
public class JdbcTemplateTest {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
public void testInsert() {
String sql = "insert into new_table(age, name) values (?, ?)";
List<Student> studentList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
Student student = new Student();
student.setAge(18);
student.setName("你好");
studentList.add(student);
}
int[][] array = jdbcTemplate.batchUpdate(sql, studentList, 10, new InsertStudentSetter());
System.out.println(JSON.toJSONString(array));
}
}
输出结果:
[[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1,1,1]]
studentList 是全量数据,studentList 后面的 int 参数是每一批次执行多少个语句,所以返回二维数组,最里面数组的数字是 insert 或者 update 语句的受影响行数。