← Back to Chapters

Batch Processing

⚙️ Batch Processing

? Quick Overview

Batch processing in Advance Java allows executing multiple database operations together as a single unit. It significantly improves performance by reducing database round-trips and is widely used in bulk inserts, updates, and deletes.

? Key Concepts

  • Execute multiple SQL statements in one request
  • Improves performance for large datasets
  • Commonly used with JDBC
  • Reduces network and database overhead

? Syntax / Theory

In JDBC, batch processing is achieved using addBatch() and executeBatch(). Statements are collected and sent to the database together instead of one by one.

? View Code Example
// Example of JDBC batch insert operation
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb","root","password");

PreparedStatement ps = con.prepareStatement(
"INSERT INTO student(name, age) VALUES(?, ?)");

ps.setString(1, "Amit");
ps.setInt(2, 22);
ps.addBatch();

ps.setString(1, "Neha");
ps.setInt(2, 21);
ps.addBatch();

ps.executeBatch();
con.close();

?️ Live Output / Explanation

Both records are inserted into the database in a single batch execution, improving speed compared to individual inserts.

? Interactive Simulator: The Network Trip

Visualizing the difference between inserting 5 records Sequentially vs Batching.

? Java App
 
5x
?️ Database
Ready to simulate...

? Tips & Best Practices

  • Use batch size limits for very large datasets
  • Always use transactions with batch processing
  • Handle exceptions using batch update counts
  • Prefer PreparedStatement over Statement

? Try It Yourself

  1. Create a table and insert 1000 records using batch processing
  2. Compare execution time with single insert queries
  3. Modify the example to perform batch updates