Java Reference
In-Depth Information
Listing 7.3
Local transaction
public void runStatementsUsingLocalTransactions() {
SqlMapClient sqlMapClient =
SqlMapClientConfig.getSqlMapClient();
try {
sqlMapClient.startTransaction();
Person p =
(Person)sqlMapClient.queryForObject
("getPerson", new Integer(9));
p.setLastName("Smith");
sqlMapClient.update("updatePerson", p);
Department d =
(Department)sqlMapClient.queryForObject
("getDept", new Integer(3));
p.setDepartment(d);
sqlMapClient.update("updatePersonDept", p);
sqlMapClient.commitTransaction();
} finally {
sqlMapClient.endTransaction();
}
}
The two update statements in listing 7.3 will be run within the same transaction,
and therefore if either one fails, both will fail.
It's very important to note the try/finally block that surrounds the transac-
tion demarcation methods. This pattern ensures that the transaction will be prop-
erly ended, even in the event of an error. Using a try/finally block is simpler
and more effective than using a try/catch block, because it doesn't require you to
catch an exception that you probably can't do anything with anyway.
7.4 Global transactions
Global transactions define a much wider transaction scope than local transactions
do. They can involve other databases, message queues, and even other applica-
tions. Figure 7.2 shows such systems and illustrates just how complicated global
transactions can become.
Luckily, as far as i BATIS goes, using a global transaction isn't any harder than
using a local one. But, there are some things to be aware of, as well as some
choices to make, some of which are best discovered through trial and error.
Search WWH ::




Custom Search