Dec 12, 2013

Spring JdbcTemplate batch updates and inserts

The query doesn't need to be repeatedly parsed. Parsed only once per batch.

The values are transmitted in one network round-trip to the server. So, only one remote call.

The commands can be placed inside a single transaction when run in a transnational context.

Q. Should batch updates run within a transaction?

A. Yes. It is important to keep in mind, that each update added to a Statement or PreparedStatement is executed separately by the database. So, to avoid some data succeeding and others failing you need to run them inside a transaction. When executed inside a transaction, either all updates succeed or all fail, leaving the data in a consistent state.

Q. What type of statement is used for the batch updates?

A. PreparedStatement.

Q. How will you perform a batch update using the Spring JdbcTemplate?

A. The example below is used for an update SQL, but it can be used in a similar fashion for inserts and deletes as well. Spring issues multiple update statements on a single PreparedStatement. There are two ways to do this.