专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

四十二、5.6 声明式事务

文章永久连接:https://tech.souyunku.com/8316

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 并不支持事务。

干货推荐

未经允许不得转载:搜云库技术团队 » 四十二、5.6 声明式事务

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们