參考 http://my.oschina.net/lhplj/blog/341555 java
public boolean transferMoney(Serializable fromId, Serializable toId, int tradeMoney) { // 標識 boolean flag = false; // String sql[] = new String[2]; sql[0] = "update BankAccount ba set ba.balance = ba.balance - " + tradeMoney + " where ba.id='" + fromId + "'"; sql[1] = "update BankAccount ba set ba.balance = ba.balance + " + tradeMoney + " where ba.id='" + toId + "'"; // 事務 DefaultTransactionDefinition def = new DefaultTransactionDefinition(); DataSourceTransactionManager transactionManager = new DataSourceTransactionManager( jt.getDataSource()); TransactionStatus status = transactionManager.getTransaction(def); // 執行結果 int result[] = new int[sql.length]; // 批量執行 result = this.jt.batchUpdate(sql); // 是否提交事務 boolean commit = true; for (int j = 0; j < result.length; j++) { if (result[j] == 0) { // 錯誤執行 commit = false; transactionManager.rollback(status); break; } } // 成功才提交事務 if (commit) { transactionManager.commit(status); flag = true; } // 返回 return flag; }