当前位置:K88软件开发文章中心网站服务器框架JFinal → 文章内容

5.6 声明式事务

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-25 14:21:55

由 厦门小懒懒 创建, 最后一次修改 2016-10-06 ActiveRecord 支持声名式事务,声明式事务需要使用 ActiveRecordPlugin 提供的拦截器来 实现,拦截器的配置方法见 Interceptor 有关章节。以下代码是声明式事务示例:// 本例仅为示例, 并未严格考虑账户状态等业务逻辑@Before(Tx.class)public void trans_demo() {// 获取转账金额Integer transAmount = getParaToInt("transAmount");// 获取转出账户idInteger fromAccountId = getParaToInt("fromAccountId");// 获取转入账户idInteger 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 并不支持事务。

5.6 声明式事务