JFinal 的事務有兩種面孔:宣告式的 @Before(Tx.class),以及程式化呼叫的 Db.tx(...)。兩者最終都在做同一件事——把連線、隔離等級、自動提交與提交/回滾綁成一個完整流程。
Tx 本身就是一個攔截器,加上註解後,方法體內的所有 DML 操作都落在同一個事務裡。
@Before(Tx.class)
public void savePost() {
// 這裡的資料庫操作全部同一事務
}
public void intercept(Invocation inv) {
Config config = getConfigWithTxConfig(inv);
if (config == null) config = DbKit.getConfig();
Connection conn = config.getThreadLocalConnection();
// 已有連線代表處於巢狀事務中,只需必要時提高隔離等級後直接放行
if (conn != null) {
try {
if (conn.getTransactionIsolation() < getTransactionLevel(config))
conn.setTransactionIsolation(getTransactionLevel(config));
inv.invoke();
return;
} catch (SQLException e) {
throw new ActiveRecordException(e);
}
}
Boolean autoCommit = null;
try {
conn = config.getConnection(); // 1. 建立連線
autoCommit = conn.getAutoCommit();
config.setThreadLocalConnection(conn);
conn.setTransactionIsolation(getTransactionLevel(config)); // 2. 隔離等級
conn.setAutoCommit(false); // 3. 手動提交
inv.invoke(); // 4. 執行業務
conn.commit(); // 5. 提交
} catch (NestedTransactionHelpException e) {
// 巢狀事務回傳 false,外層必須一起回滾
if (conn != null) try { conn.rollback(); } catch (Exception e1) { LogKit.error(e1.getMessage(), e1); }
LogKit.logNothing(e);
} catch (Throwable t) {
if (conn != null) try { conn.rollback(); } catch (Exception e1) { LogKit.error(e1.getMessage(), e1); } // 6. 回滾
throw t instanceof RuntimeException ? (RuntimeException) t : new ActiveRecordException(t);
} finally {
try {
if (conn != null) {
if (autoCommit != null) conn.setAutoCommit(autoCommit); // 還原設定
conn.close();
}
} catch (Throwable t) {
LogKit.error(t.getMessage(), t); // 這裡不能再拋,否則會蓋掉 catch 中更重要的例外
} finally {
config.removeThreadLocalConnection(); // 避免 ThreadLocal 洩漏
}
}
}
值得注意的兩個細節:finally 中刻意吞掉例外,以免掩蓋真正的業務錯誤;以及 removeThreadLocalConnection 必須執行,否則在執行緒池環境下會造成連線洩漏。
Tx 採用 JFinal 預設的隔離等級,定義在 DbKit 中:
public static final int DEFAULT_TRANSACTION_LEVEL = Connection.TRANSACTION_REPEATABLE_READ;
其餘幾個攔截器都繼承 Tx,唯一差別就是覆寫 getTransactionLevel 回傳不同常量。以 TxReadCommitted 為例:
public class TxReadCommitted extends Tx {
/** 禁止髒讀,但不可重複讀與幻讀仍可能發生 */
private int TRANSACTION_READ_COMMITTED = 2;
@Override
protected int getTransactionLevel(Config config) {
return TRANSACTION_READ_COMMITTED;
}
}
另一條路不靠攔截器,而是把一段邏輯包成 IAtom 交給 DbPro.tx 執行:
boolean tx(Config config, int transactionLevel, IAtom atom) {
Connection conn = config.getThreadLocalConnection();
if (conn != null) { // 巢狀事務
try {
if (conn.getTransactionIsolation() < transactionLevel)
conn.setTransactionIsolation(transactionLevel);
boolean result = atom.run();
if (result) return true;
// 巢狀回傳 false 時不可直接 return false,必須通知外層一起回滾
throw new NestedTransactionHelpException("Notice the outer transaction that the nested transaction return false");
} catch (SQLException e) {
throw new ActiveRecordException(e);
}
}
Boolean autoCommit = null;
try {
conn = config.getConnection(); // 1. 建立連線
autoCommit = conn.getAutoCommit();
config.setThreadLocalConnection(conn);
conn.setTransactionIsolation(transactionLevel); // 2. 隔離等級
conn.setAutoCommit(false); // 3. 手動提交
boolean result = atom.run(); // 4. 執行所有 DML
if (result) conn.commit(); else conn.rollback();// 5. 全成功提交,否則回滾
return result;
} catch (NestedTransactionHelpException e) {
if (conn != null) try { conn.rollback(); } catch (Exception e1) { LogKit.error(e1.getMessage(), e1); }
LogKit.logNothing(e);
return false;
} catch (Throwable t) {
if (conn != null) try { conn.rollback(); } catch (Exception e1) { LogKit.error(e1.getMessage(), e1); }
throw t instanceof RuntimeException ? (RuntimeException) t : new ActiveRecordException(t);
} finally {
// 還原 autoCommit、關閉連線、清除 ThreadLocal,同 Tx
}
}
兩種寫法可以這樣選:方法上下的業務邏輯用 @Before(Tx.class) 最省事;需要在動態組裝的流程中決定是否成敗,或想明確控制回滾點,就用 Db.tx 搭配 IAtom,讓 run() 回傳 false 觸發回滾。