JDBCmedium3-5 years

Why does JDBC batching speed up a bulk insert, and what's the difference between plain addBatch()/executeBatch() and a driver's rewriteBatchedInserts setting?

Inserting rows one at a time means one network round trip per row, and when the database is a network hop away, waiting for each round trip dominates the actual insert cost. addBatch() accumulates parameter sets in the driver's memory with no network activity; executeBatch() sends them together, cutting the number of round trips your code waits on from one-per-row to one-per-chunk. reWriteBatchedInserts (PostgreSQL) and rewriteBatchedStatements (MySQL) go a step further: instead of just packing many "execute this row" messages into fewer round trips, the driver rewrites the whole batch into one genuinely different SQL statement with many value tuples (insert into t values (1,'a'),(2,'b'),...), so the database parses and plans one statement instead of N.

The lesson behind it →
More on JDBC