Declarative transactions
ActiveRecord supports declarative transactions. Declarative transactions need to be implemented using the interceptor provided by ActiveRecordPlugin. For the configuration method of the interceptor, see the relevant chapters of Interceptor. The following code is an example of declarative transaction:
@Before(Tx.class)
public void trans_demo () {
// Get the transfer amount
Integer transAmount = getParaToInt("transAmount");
// Get the transfer account id
Integer fromAccountId = getParaToInt("fromAccountId");
// Get the transfer account id
Integer toAccountId = getParaToInt("toAccountId");
// Transfer operation
Db.update("update account set cash = cash - ? where id = ?", transAmount, fromAccountId);
// Transfer operation
Db.update("update account set cash = cash + ? where id = ?", transAmount, toAccountId);
}
In the above code, only one Tx interceptor is declared to add transaction support to the action. In addition, ActiveRecord is also equipped with TxByActionKeys, TxByActionKeyRegex, TxByMethods, and TxByMethodRegex, which respectively support actionKeys, actionKey regular, actionMethods, and actionMethod regular declarative transactions. The following is an example code:
me.add(new TxByActionKeyRegex("/trans.*")); me.add(new TxByActionKeys("/tx/save", " /tx/update"));
Note: The MySql database table must be set to the InnoDB engine to support transactions. MyISAM does not support transactions.