展开全部
5.7 声明62616964757a686964616fe59b9ee7ad9431333365646333式事务
ActiveRecord支持声明式事务,声明式事务需要使用ActiveRecordPlugin提供的拦截器来实现,拦截器的配置方法见Interceptor有关章节。以下代码是声明式事务示例:// 本例仅为示例, 并未严格考虑账户状态等业务逻辑
@Before(Tx.class)
public void trans_demo() {
// 获取转账金额
Integer transAmount = getParaToInt("transAmount");
// 获取转出账户id
Integer fromAccountId = getParaToInt("fromAccountId");
// 获取转入账户id
Integer toAccountId = getParaToInt("toAccountId");
// 转出操作
Db.update("update account set cash = cash - ? where id = ?",
transAmount, fromAccountId);
// 转入操作
Db.update("update account set cash = cash + ? where id = ?",
transAmount, toAccountId);
}
以上代码中,仅声明了一个Tx拦截器即为action添加了事务支持。除此之外ActiveRecord还配备了TxByActionKeys、TxByActionKeyRegex、TxByMethods、TxByMethodRegex,分别支持actionKeys、actionKey正则、actionMethods、actionMethod正则声明式事务,以下是示例代码: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拦截器可通过传入正则表达式对action进行拦截,当actionKey被正则匹配上将开启事务。TxByActionKeys可以对指定的actionKey进行拦截并开启事务,TxByMethods可以对指定的method进行拦截并开启事务。
注意:MySql数据库表必须设置为InnoDB引擎时才支持事务,MyISAM并不支持事务。