Batch execution using java.sql.PreparedStatement
allows you to execute a single DML statement with multiple sets of values for its parameters.
This example demonstrates how to prepare an insert statement and use it to insert multiple rows in a batch.
Connection connection = ...; // obtained earlier
connection.setAutoCommit(false); // disabling autoCommit is recommend for batching
int orderId = ...; // The primary key of inserting and order
List<OrderItem> orderItems = ...; // Order item data
try (PreparedStatement insert = connection.prepareStatement(
"INSERT INTO orderlines(orderid, itemid, quantity) VALUES (?, ?, ?)")) {
// Add the order item data to the batch
for (OrderItem orderItem : orderItems) {
insert.setInt(1, orderId);
insert.setInt(2, orderItem.getItemId());
insert.setInt(3, orderItem.getQuantity());
insert.addBatch();
}
insert.executeBatch();//executing the batch
}
connection.commit();//commit statements to apply changes