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
java
package com.example.shop.repository; import com.example.shop.domain.Order; import com.example.shop.domain.OrderStatus;
Deriving JPA queries from method names in Spring
query derivation
repositories
pagination
Intermediate
8 steps
ruby
class BulkImporter BATCH_SIZE = 500 def initialize(records)
Batching bulk inserts in Rails
batching
bulk-insert
deduplication
Intermediate
5 steps
java
import java.util.List; import java.util.IntSummaryStatistics; public class OrderReport {
Aggregating stats with IntSummaryStatistics
streams
aggregation
records
Intermediate
5 steps
java
@RestControllerAdvice public class GlobalExceptionHandler { private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
Centralized error handling in Spring
exception-handling
problemdetail
rest-api
Intermediate
7 steps
ruby
class CartMergeService def initialize(guest_cart:, user_cart:) @guest_cart = guest_cart @user_cart = user_cart
Merging a guest cart into a user cart in Rails
service object
transactions
idempotency
Intermediate
7 steps
java
public List<String> collectTagsFromArticles(List<Article> articles) { return articles.stream() .flatMap(article -> article.getTags().stream()) .map(String::trim)
Flattening nested data with Java streams
streams
flatmap
collectors
Intermediate
7 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.