JTA 事務處理
public void transferAccount() {
UserTransaction userTx = null;
Connection connA = null;
Statement stmtA = null;
Connection connB = null;
Statement stmtB = null;
try{
// 獲得 Transaction 管理對象
userTx = (UserTransaction)getContext().lookup("\
java:comp/UserTransaction");
// 從數據庫 A 中取得數據庫連接
connA = getDataSourceA().getConnection();
// 從數據庫 B 中取得數據庫連接
connB = getDataSourceB().getConnection();
// 啓動事務
userTx.begin();
// 將 A 賬戶中的金額減少 500
stmtA = connA.createStatement();
stmtA.execute("
update t_account set amount = amount - 500 where account_id = 'A'");
// 將 B 賬戶中的金額增加 500
stmtB = connB.createStatement();
stmtB.execute("\
update t_account set amount = amount + 500 where account_id = 'B'");
// 提交事務
userTx.commit();
// 事務提交:轉賬的兩步操作同時成功(數據庫 A 和數據庫 B 中的數據被同時更新)
} catch(SQLException sqle){
try{
// 發生異常,回滾在本事務中的操縱
userTx.rollback();
// 事務回滾:轉賬的兩步操作完全撤銷
//( 數據庫 A 和數據庫 B 中的數據更新被同時撤銷)
stmt.close();
conn.close();
...
}catch(Exception ignore){
}
sqle.printStackTrace();
} catch(Exception ne){
e.printStackTrace();
}
}