标签详细说明带范例代码9

标签详细说明带实例代码9
自动的事务处理
虽然极力推荐使用明确划分的事务范围,在简单需求(通常使只读)的情况下,可以使用简化的语法。如果您没有使用startTransaction(),commitTransation()和rollbackTransaction()方法来明确地划分事务范围,事务将会自动执行。例如:
private Reader reader = new Resources.getResourceAsReader
("com/ibatis/example/sqlMapconfig.xml");
private SqlMapClient sqlMap = XmlSqlMapBuilder.buildSqlMap(reader);
public updateItemDescription (String itemId, String newDescription) throws SQLException {
try {
Item item = (Item) sqlMap.queryForObject ("getItem", itemId);
item.setDescription (“TX1”);
//No transaction demarcated, so transaction will be automatic (implied)
sqlMap.update ("updateItem", item);
item.setDescription (newDescription);
item.setDescription (“TX2”);
//No transaction demarcated, so transaction will be automatic (implied)
sqlMap.update("updateItem", item);} catch (SQLException e) {
throw (SQLException) e.fillInStackTrace();
}
}
注意!使用自动事务处理要非常小心。虽然看起来很有吸引力,但如果有多个数据更新操作要在同一事务中处理时,您会遇到麻烦。在上面的例子中,如果第二个“updateItem”操作失败,第一个“updateItem”操作仍然会执行,description会更新成“TX1”。
全局(分布式)事务
SQL Map框架支持全局事务。全局事务也叫分布式事务,它可以允许您在同一事务中更新多个数据库(或其他符合JTA规范的资源),即同时成功或失败。