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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Batching writes in fixed-size chunks amortizes round-trips to the database instead of one call per row.
- 2Disabling auto-commit and committing once makes the whole insert atomic, with rollback on any failure.
- 3Saving and restoring the connection's original auto-commit state keeps pooled connections clean for reuse.
Related explainers
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/batched-jdbc-inserts-with-transaction-safety-explained-java-c5b3/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.