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.
In JDBC, batch processing is achieved using addBatch() and executeBatch(). Statements are collected and sent to the database together instead of one by one.
// 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();
Both records are inserted into the database in a single batch execution, improving speed compared to individual inserts.
Visualizing the difference between inserting 5 records Sequentially vs Batching.
PreparedStatement over Statement