java 50 lines · 8 steps

Batched JDBC inserts with transaction safety

A repository inserts many orders efficiently by batching writes and wrapping them in a single rolled-back-on-failure transaction.

Explained by highlit
1public class OrderRepository {
2 
3 private static final int BATCH_SIZE = 500;
4 private static final String INSERT_SQL =
5 "INSERT INTO orders (customer_id, product_sku, quantity, total_cents, created_at) " +
6 "VALUES (?, ?, ?, ?, ?)";
7 
8 private final DataSource dataSource;
9 
10 public OrderRepository(DataSource dataSource) {
11 this.dataSource = dataSource;
12 }
13 
14 public int[] saveAll(List<Order> orders) throws SQLException {
15 List<Integer> results = new ArrayList<>();
16 
17 try (Connection conn = dataSource.getConnection();
18 PreparedStatement ps = conn.prepareStatement(INSERT_SQL)) {
19 
20 boolean previousAutoCommit = conn.getAutoCommit();
21 conn.setAutoCommit(false);
22 
23 try {
24 int count = 0;
25 for (Order order : orders) {
26 ps.setLong(1, order.getCustomerId());
27 ps.setString(2, order.getProductSku());
28 ps.setInt(3, order.getQuantity());
29 ps.setLong(4, order.getTotalCents());
30 ps.setTimestamp(5, Timestamp.from(order.getCreatedAt()));
31 ps.addBatch();
32 
33 if (++count % BATCH_SIZE == 0) {
34 for (int r : ps.executeBatch()) results.add(r);
35 }
36 }
37 for (int r : ps.executeBatch()) results.add(r);
38 
39 conn.commit();
40 } catch (SQLException e) {
41 conn.rollback();
42 throw e;
43 } finally {
44 conn.setAutoCommit(previousAutoCommit);
45 }
46 }
47 
48 return results.stream().mapToInt(Integer::intValue).toArray();
49 }
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Batching writes in fixed-size chunks amortizes round-trips to the database instead of one call per row.
  2. 2Disabling auto-commit and committing once makes the whole insert atomic, with rollback on any failure.
  3. 3Saving and restoring the connection's original auto-commit state keeps pooled connections clean for reuse.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Batched JDBC inserts with transaction safety — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code