reWriteBatchedInserts 是 PostgreSQL JDBC 驱动 提供的一个优化选项,它可以 重写批量插入语句,从而提高插入性能。
作用
当 reWriteBatchedInserts=true 时,PostgreSQL JDBC 驱动会将 多个单独的 INSERT 语句 转换为 一个多行 INSERT 语句,减少数据库的交互次数,提高性能。例如:
默认批量插入(未优化)
INSERT INTO test(name) VALUES ('A');
INSERT INTO test(name) VALUES ('B');
INSERT INTO test(name) VALUES ('C');
启用 reWriteBatchedInserts=true 后
INSERT INTO test(name) VALUES ('A'), ('B'), ('C');
这样可以 减少 SQL 解析和执行的开销,提高插入速度 2-3 倍。
如何使用
在 JDBC 连接 URL 中启用:
String url = "jdbc:postgresql://localhost:5432/mydb?reWriteBatchedInserts=true";
Connection conn = DriverManager.getConnection(url, user, password);
或者在 Spring Boot 配置:
spring:
datasource:
url: jdbc:postgresql://localhost:5432/mydb?reWriteBatchedInserts=true
注意事项
-
仅适用于
INSERT语句,UPDATE和DELETE不受影响。 -
启用executeBatch()返回值变化:reWriteBatchedInserts=true后,executeBatch()返回的int[]可能包含-2,表示 成功但影响行数未知。 -
适用于 PostgreSQL 9.0 及以上版本。
Initializing the Driver | pgJDBC



















