Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Insert 100,000 rows efficiently using JdbcTemplate. Show the API and explain the driver setting that matters for MySQL and PostgreSQL.

We call jdbcTemplate.batchUpdate(sql, items, 1000, (ps, it) -> { ps.setString(1, it.name()); ps.setBigDecimal(2, it.price()); }), which sends the 100,000 parameter sets in chunks of 1,000, each chunk as one batch instead of 1,000 round trips. The driver setting that matters is statement rewriting: MySQL Connector/J needs rewriteBatchedStatements=true and PostgreSQL's driver has reWriteBatchedInserts=true, both turning a batch of single-row inserts into multi-row inserts. We run the load in one transaction or commit per chunk, depending on how we want failures handled.

Why this question is asked

Inserting rows one at a time is the most common reason a data import takes an hour instead of a minute. The database itself is rarely the bottleneck; the network round trips and per-statement overhead are. Interviewers ask this to see whether we know the batching API, the driver flag that makes it really fast, and the transaction choice that decides what happens on failure. In this answer, we will see why single inserts are slow, write the batch with JdbcTemplate, explain the driver rewrite settings for MySQL and PostgreSQL, choose a transaction strategy, and check the results.

1Why One Insert at a Time Is Slow

Each separate insert costs a round trip: the application sends the statement, waits for the database to execute it, and waits for the reply. If the database is 0.5 ms away on the network, 100,000 inserts spend at least 50 seconds just waiting, before counting parsing, execution and commits. In auto-commit mode it is worse, because every insert is also its own transaction with its own commit, and each commit waits for the write-ahead log to reach disk.

JDBC batching fixes the round-trip part. Instead of executing each statement, we add parameter sets to a batch with addBatch() and send them all with executeBatch(). The driver then sends many executions together, and the database processes them with far fewer waits.

2Writing the Batch With JdbcTemplate

JdbcTemplate has an overload made for this: it takes the SQL, a collection of items, a batch size and a setter that copies one item's values into the PreparedStatement.

Java
record Item(String name, BigDecimal price) {}
@Transactional
public void insertAll(List<Item> items) { // 100,000 items
int[][] counts = jdbcTemplate.batchUpdate(
"insert into item(name, price) values (?, ?)",
items,
1000, // rows per executeBatch()
(ps, it) -> {
ps.setString(1, it.name());
ps.setBigDecimal(2, it.price());
});
// counts.length == 100 (one array per chunk)
// counts[0].length == 1000 (one count per row in the chunk)
}

Notice what the batch size does. JdbcTemplate does not send all 100,000 rows in one executeBatch; it adds 1,000, executes, and repeats. That keeps memory bounded on both sides, because the driver buffers a chunk at a time, and it gives the database statements of a reasonable size. Values between a few hundred and a few thousand work well; we measure to choose. The return value is an int[][] of update counts per chunk and per row.

3The Driver Setting That Matters

Batching alone removes round trips, but many drivers still send each row as a separate INSERT inside the batch. The database still parses and executes 100,000 statements. Rewriting goes further: the driver combines many single-row inserts into one multi-row insert, so the database runs one statement per group.

Text
# MySQL Connector/J
spring.datasource.url=jdbc:mysql://db:3306/shop?rewriteBatchedStatements=true
# PostgreSQL JDBC
spring.datasource.url=jdbc:postgresql://db:5432/shop?reWriteBatchedInserts=true
-- what the database receives for one chunk, with rewriting:
-- insert into item(name, price) values (?, ?), (?, ?), (?, ?), ... (many rows per statement)
What the database receives for 100,000 rows
ApproachRound trips (approx.)Statements executed
One insert per call, auto-commit100,000 plus 100,000 commits100,000
Batch of 1,000, no rewrite (MySQL)about 100,000; little gain100,000
Batch of 1,000, no rewrite (PostgreSQL)about 100, pipelined100,000
Batch of 1,000 with rewriteabout 100a few hundred multi-row inserts
Rewriting matters most on MySQL; on PostgreSQL batching already removes most round trips.

For MySQL, rewriteBatchedStatements=true is the difference between a batch that is only a little faster and one that is many times faster, because without it Connector/J sends each statement of the batch separately. For PostgreSQL, pgjdbc already pipelines a batch efficiently, so the gain is smaller but still real for inserts; reWriteBatchedInserts=true groups rows into multi-row INSERTs. Notice the different spelling and capitalisation of the two properties, which is a common source of silently ignored settings.

There is a side effect: with rewriting, the update count per row is often not known, and the driver reports Statement.SUCCESS_NO_INFO, which is -2, for each row instead of 1. Code that checks for 1 must accept -2 as success.

4One Transaction or a Commit per Chunk

The last decision is about failure. If we annotate the method with @Transactional, as above, all 100,000 rows are one transaction. If any row fails, for example on a constraint, everything rolls back and the table is unchanged. That is simple to reason about and fast, because there is only one commit, but a failure at row 99,000 throws away all the work, and a very long transaction holds locks and, in PostgreSQL, delays cleanup of old row versions.

The alternative is a transaction per chunk, which we can do with TransactionTemplate around each slice of the list. Each chunk of 1,000 commits independently; if chunk 57 fails, chunks 1 to 56 stay committed, and we record where we stopped so a restart can continue from chunk 57. That suits imports that must make progress and can be resumed, at the cost of a partially loaded table between runs.

Java
for (List<Item> chunk : Lists.partition(items, 1000)) { // Guava, or our own slicing
tx.executeWithoutResult(s -> jdbcTemplate.batchUpdate(SQL, chunk, chunk.size(), SETTER));
progress.record(chunk); // to resume after a failure
}

5Checking the Results

After the load, we verify instead of assuming. A count of the inserted rows, or of a load id column, confirms that 100,000 arrived. Timing each chunk shows whether the batch size is sensible and whether rewriting took effect: with MySQL, a load that does not speed up after adding the flag usually means the URL property is misspelt or overridden. Database statement statistics, such as pg_stat_statements on PostgreSQL, show whether the server ran thousands of single-row inserts or a few hundred multi-row ones.

For far larger loads, tens of millions of rows into PostgreSQL, COPY through the driver's CopyManager is faster still, because it skips per-statement processing altogether.

6Follow-up questions

Does Hibernate batch inserts too?

It can, with hibernate.jdbc.batch_size set and order_inserts enabled, but not for entities with IDENTITY primary keys, because Hibernate needs each generated id immediately after each insert. Sequences with a pooled optimiser allow batching. For bulk loads where we do not need managed entities, JdbcTemplate batching is simpler and faster.

Why not put all 100,000 rows in a single executeBatch?

It works, but the driver must hold all 100,000 parameter sets in memory, and the database receives one enormous request, which makes failures harder to locate and can hit protocol limits. Chunks of around a thousand rows give nearly all of the speed with bounded memory and clearer progress.

What does the int[][] of update counts tell us?

One array per chunk and one entry per row, normally 1 for each inserted row. With driver rewriting, entries are often Statement.SUCCESS_NO_INFO (-2), meaning success without a count. If a row fails, the driver throws BatchUpdateException, which Spring translates into a DataAccessException, so counts are mainly useful for sanity checks rather than error detection.

7Conclusion

In this answer, we saw that single-row inserts are slow because of round trips and per-statement work, and that jdbcTemplate.batchUpdate with a batch size sends rows in chunks. The driver setting that matters is statement rewriting, rewriteBatchedStatements=true for MySQL Connector/J and reWriteBatchedInserts=true for PostgreSQL, which turns many inserts into multi-row statements and may report counts as -2. We chose between one transaction and a commit per chunk based on how failures should be handled, and checked the load with counts and statement statistics.

What to say in the interviewAbout 90 seconds aloud

Open with

I would use JdbcTemplate's batchUpdate overload that takes the SQL, the collection, a batch size and a ParameterizedPreparedStatementSetter: batchUpdate("insert into item(name, price) values (?, ?)", items, 1000, (ps, it) -> { ps.setString(1, it.name()); ps.setBigDecimal(2, it.price()); }).

Then, if they want more

That sends the hundred thousand rows as a hundred executeBatch calls of a thousand rows each, so instead of a hundred thousand round trips we have about a hundred, and memory stays bounded. Then the driver setting.

On MySQL, Connector/J sends each statement of a batch separately unless rewriteBatchedStatements=true is on the JDBC URL; with it, the driver combines the inserts into multi-row insert statements, which is usually where the big speed-up comes from. PostgreSQL's driver already pipelines batches well, and reWriteBatchedInserts=true makes it rewrite inserts into multi-row form too.

I would mention that with rewriting the update counts often come back as SUCCESS_NO_INFO, minus two, instead of one. Finally, the transaction. Running the whole load in one @Transactional method means one commit and all-or-nothing behaviour, which is simple but loses everything on a late failure and holds a long transaction.

Committing per chunk with TransactionTemplate and recording progress makes the job resumable, at the cost of partial data after a failure. I would pick based on whether the import must be atomic or must make progress, and for much larger PostgreSQL loads I would consider COPY.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
java.sql, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Insert 100,000 rows efficiently using JdbcTemplate. Show the API and explain the driver...": https://scrivio-interview-library.netlify.app/databases/jdbc/fcc574a0f0/