Java Notes
Master JDBC batch processing — Statement and PreparedStatement batching, performance optimization, error handling, and bulk data import patterns.
What is Batch Processing?
Batch processing allows you to group multiple SQL statements and send them to the database in a single network call, dramatically reducing overhead for bulk operations.
| App | DB: INSERT row 1 DB → App: OK |
| App | DB: INSERT row 2 DB → App: OK |
| App | DB: INSERT row 3 DB → App: OK |
| App | DB: [INSERT row 1, INSERT row 2, ... INSERT row 1000] |
| DB | App: [OK, OK, ... OK] |
Performance Comparison
| - Individual statements | ~45 seconds |
| - Batch (size 100) | ~3 seconds |
| - Batch (size 1000) | ~1.2 seconds |
| - Batch + rewriteBatch | ~0.4 seconds |
PreparedStatement Batch (Most Common)
Processed " + count + " records...
MySQL-Specific Optimization: rewriteBatchedStatements
// This URL parameter is CRITICAL for MySQL batch performance:
String url = "jdbc:mysql://localhost:3306/mydb?rewriteBatchedStatements=true";
// Without this flag: Sends individual INSERT statements
// INSERT INTO t VALUES (1, 'a');
// INSERT INTO t VALUES (2, 'b');
// INSERT INTO t VALUES (3, 'c');
// With this flag: Rewrites to multi-value INSERT
// INSERT INTO t VALUES (1, 'a'), (2, 'b'), (3, 'c');
// Multi-value INSERT is 10-50x faster in MySQL!Error Handling in Batch Processing
All changes rolled back
Batch with Generated Keys
public static List<Integer> batchInsertWithKeys(List<Employee> employees) throws SQLException {
String sql = "INSERT INTO employees (first_name, last_name, email, department, salary) " +
"VALUES (?, ?, ?, ?, ?)";
List<Integer> generatedIds = new ArrayList<>();
try (Connection conn = DriverManager.getConnection(url, "root", "password");
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
conn.setAutoCommit(false);
for (Employee emp : employees) {
pstmt.setString(1, emp.getFirstName());
pstmt.setString(2, emp.getLastName());
pstmt.setString(3, emp.getEmail());
pstmt.setString(4, emp.getDepartment());
pstmt.setDouble(5, emp.getSalary());
pstmt.addBatch();
}
pstmt.executeBatch();
// Retrieve generated keys
try (ResultSet keys = pstmt.getGeneratedKeys()) {
while (keys.next()) {
generatedIds.add(keys.getInt(1));
}
}
conn.commit();
}
return generatedIds;
}Performance Benchmarking
Interview Questions
Q1: What is batch processing in JDBC and why use it?
Answer: Batch processing groups multiple SQL statements into a single database call, reducing network round-trips. For bulk operations, it provides 10-50x performance improvement by minimizing network latency and enabling database-side optimizations.
Q2: What is the difference between Statement batch and PreparedStatement batch?
Answer: Statement batch can mix different SQL commands (INSERT, UPDATE, DELETE) in one batch. PreparedStatement batch executes the same SQL with different parameters — more common and more efficient because the execution plan is compiled once and reused.
Q3: What does rewriteBatchedStatements=true do in MySQL?
Answer: It rewrites individual INSERT statements into a single multi-row INSERT (INSERT INTO t VALUES (...), (...), (...)), which MySQL executes much faster. Without it, MySQL receives and processes each INSERT individually despite batching.
Q4: How do you handle errors in batch processing?
Answer: Catch BatchUpdateException, which provides getUpdateCounts() showing which statements succeeded/failed. Decide whether to rollback everything or commit partial results. Always use transactions with batch operations.
Q5: What is the optimal batch size?
Answer: Typically 500-1000 for most databases. Too small means many round-trips; too large means excessive memory usage. Benchmark with your specific database and data. For MySQL with rewriteBatchedStatements, larger batches (up to 10K) can be efficient.
Q6: Why use setAutoCommit(false) with batch processing?
Answer: Auto-commit forces a disk flush after every statement. Disabling it wraps the batch in a single transaction — one disk flush for all statements. This alone can improve performance 5-10x.
Summary
In this chapter, we learned about Batch Processing in JDBC in detail. Here are the key points:
- Basic introduction to the concept and why it is needed
- Syntax and structure with complete examples
- Internal working and best practices
- Real-world applications and use cases
- Common mistakes and how to avoid them
- How this topic is asked in interviews
To practice these concepts, write and run the code in your IDE and verify the output. Modify each example and experiment so that you deeply understand the concept.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Batch Processing in JDBC.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, jdbc, batch, processing
Related Java Master Course Topics