Java Reference
In-Depth Information
public void saveOrder(SqlMapClient sqlMapClient, Order order)
throws SQLException {
if (null == order.getOrderId()) {
sqlMapClient.insert("Order.insert", order);
} else {
sqlMapClient.update("Order.update", order);
}
sqlMapClient.delete("Order.deleteDetails", order);
for(int i=0;i<order.getOrderItems().size();i++) {
OrderItem oi = (OrderItem) order.getOrderItems().get(i);
oi.setOrderId(order.getOrderId());
sqlMapClient.insert("OrderItem.insert", oi);
}
}
While this code works adequately, it does not provide for any sort of transaction
isolation, so if the update of the last
OrderItem
fails, all of the other data is left in
an inconsistent state because the transactions happen on each insert or update. In
addition, performance is hindered because each statement is committed as soon
as it happens. In the next section, you will learn how to resolve both of those
issues using batch updates.
5.4 Running batch updates
Batch updates are one way to improve performance with i
BATIS
. By creating a
batch of statements, the driver can perform such tasks as compression to improve
performance.
One important tip for using batched statements is to wrap the batch in a single
transaction. If you fail to do so, a new transaction will be started for each state-
ment, and performance will suffer as the batch size grows.
In section 5.2.2, we saw one way to update an object that contained child
objects. There were two issues with that solution: performance and data integrity.
To remedy the second issue, we could simply wrap the method in a transaction
and roll it back if anything threw an exception while doing the update.
This would also improve performance, but we can improve it further if we also
execute the statements in a batch:
public void saveOrder(SqlMapClient sqlMapClient, Order order)
throws SQLException {
sqlMapClient.startTransaction();
try {
if (null == order.getOrderId()) {
sqlMapClient.insert("Order.insert", order);


