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:

// This example is only an example, and business logic such as account status is not strictly considered
@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:

public void configInterceptor(Interceptors me) { me.add(new TxByMethodRegex("(.*save.*|.*update.*)")); me.add( new TxByMethods("save", "update"));

me.add(new TxByActionKeyRegex("/trans.*")); me.add(new TxByActionKeys("/tx/save", " /tx/update"));



#TxByRegex interception in the above example The controller can intercept the action by passing in a regular expression. When the actionKey is matched by the regular expression, the transaction will be started. TxByActionKeys can intercept the specified actionKey and start the transaction, and TxByMethods can intercept the specified method and start the transaction.

Note: The MySql database table must be set to the InnoDB engine to support transactions. MyISAM does not support transactions.