JFinal - 事务实现的原理
使用声明式事务
事务类本身就是一个拦截器,可以用注解的方式配置。方法内部的所有 DML 操作都将在本次事务之内。
配置代码如下:
@Before(Tx.class)
public void savePost(){
//...
}
事务配置就是这么简单任性。

声明式事务实现原理
上述配置中为 savePost() 配置了事务也就是拦截器 Tx,当调用到 savePost() 的时候,是会进入到 Tx 的 intercept 方法中的:
- 建立数据库连接;
- 设置事务隔离级别;
- 设置事务手动提交;
- 反射机制调用 savePost();
- 事务提交;
- 若事务失败,就回滚。
主要代码如下:
public void intercept(Invocation inv) {
Config config = getConfigWithTxConfig(inv);
if (config == null)
config = DbKit.getConfig();
Connection conn = config.getThreadLocalConnection();
// 下面这段支持嵌套事务,可以忽略不看
if (conn != null) {
try {
if (conn.getTransactionIsolation() < getTransactionLevel(config))
conn.setTransactionIsolation(getTransactionLevel(config));
inv.invoke();
return ;
} catch (SQLException e) {
throw new ActiveRecordException(e);
}
}
Boolean autoCommit = null;
try {
// 1. 建立数据库连接
conn = config.getConnection();
autoCommit = conn.getAutoCommit();
config.setThreadLocalConnection(conn);
// 2. 设置事务隔离级别
conn.setTransactionIsolation(getTransactionLevel(config)); // conn.setTransactionIsolation(transactionLevel);
// 3. 设置事务手动提交
conn.setAutoCommit(false);
// 4. 反射机制调用 savePost()
inv.invoke();
// 5. 事务提交
conn.commit();
} catch (NestedTransactionHelpException e) {
if (conn != null) try {conn.rollback();} catch (Exception e1) {LogKit.error(e1.getMessage(), e1);}
LogKit.logNothing(e);
} catch (Throwable t) {
// 6. 若有异常就回滚
if (conn != null) try {conn.rollback();} catch (Exception e1) {LogKit.error(e1.getMessage(), e1);}
throw t instanceof RuntimeException ? (RuntimeException)t : new ActiveRecordException(t);
}
finally {
try {
if (conn != null) {
if (autoCommit != null)
conn.setAutoCommit(autoCommit);
conn.close();
}
} catch (Throwable t) {
LogKit.error(t.getMessage(), t); // can not throw exception here, otherwise the more important exception in previous catch block can not be thrown
}
finally {
config.removeThreadLocalConnection(); // prevent memory leak
}
}
}
事务隔离级别
Tx.java 使用的是 JFinal 默认配置的事务隔离级别,是在 DbKit.java 中配置的
public static final int DEFAULT_TRANSACTION_LEVEL = Connection.TRANSACTION_REPEATABLE_READ;
JFinal 还有几个拦截器,可以根据事务隔离级别的需求选用。

它们都继承与 Tx.java,唯一不同的就是事务隔离级别。
以 TxReadCommitted 为例。
继承 Tx.java,覆盖了 getTransactionLevel 方法,返回常量值,这个常量就代表了事务隔离级别。
public class TxReadCommitted extends Tx {
/**
* A constant indicating that
* dirty reads are prevented; non-repeatable reads and phantom
* reads can occur. This level only prohibits a transaction
* from reading a row with uncommitted changes in it.
*/
private int TRANSACTION_READ_COMMITTED = 2;
@Override
protected int getTransactionLevel(com.jfinal.plugin.activerecord.Config config) {
return TRANSACTION_READ_COMMITTED;
}
}
另一种实现事务的方式

这种实现方式并没有使用拦截器。
跟踪代码最终追到 DbPro.java 如下代码中:
boolean tx(Config config, int transactionLevel, IAtom atom) {
Connection conn = config.getThreadLocalConnection();
if (conn != null) { // Nested transaction support
try {
if (conn.getTransactionIsolation() < transactionLevel)
conn.setTransactionIsolation(transactionLevel);
boolean result = atom.run();
if (result)
return true;
throw new NestedTransactionHelpException("Notice the outer transaction that the nested transaction return false"); // important:can not return false
}
catch (SQLException e) {
throw new ActiveRecordException(e);
}
}
Boolean autoCommit = null;
try {
// 1. 建立数据库连接
conn = config.getConnection();
autoCommit = conn.getAutoCommit();
config.setThreadLocalConnection(conn);
// 2. 设置事务隔离级别
conn.setTransactionIsolation(transactionLevel);
// 3. 设置事务手动提交
conn.setAutoCommit(false);
// 4. 所有 DML 操作是否都执行成功?
boolean result = atom.run();
// 5. 都成功:提交;不是都成功:回滚
if (result)
conn.commit();
else
conn.rollback();
return result;
} catch (NestedTransactionHelpException e) {
if (conn != null) try {conn.rollback();} catch (Exception e1) {LogKit.error(e1.getMessage(), e1);}
LogKit.logNothing(e);
return false;
} catch (Throwable t) {
if (conn != null) try {conn.rollback();} catch (Exception e1) {LogKit.error(e1.getMessage(), e1);}
throw t instanceof RuntimeException ? (RuntimeException)t : new ActiveRecordException(t);
} finally {
try {
if (conn != null) {
if (autoCommit != null)
conn.setAutoCommit(autoCommit);
conn.close();
}
} catch (Throwable t) {
LogKit.error(t.getMessage(), t); // can not throw exception here, otherwise the more important exception in previous catch block can not be thrown
} finally {
config.removeThreadLocalConnection(); // prevent memory leak
}
}
}
主要事务流程:
- 建立数据库连接;
- 设置事务隔离级别;
- 设置事务手动提交;
- 调用 Atom 的 run 方法,所有 DML 操作是否都执行成功? 若都成功则事务提交,反之事务回滚。
JFinal - 事务实现的原理的更多相关文章
- TCC分布式事务的实现原理(转载 石杉的架构笔记)
拜托,面试请不要再问我TCC分布式事务的实现原理![石杉的架构笔记] 原创: 中华石杉 目录 一.写在前面 二.业务场景介绍 三.进一步思考 四.落地实现TCC分布式事务 (1)TCC实现阶段一:Tr ...
- mysql 事务的实现原理
开篇 相信大家都用过事务以及了解他的特点,如原子性(Atomicity),一致性(Consistency),隔离型(Isolation)以及持久性(Durability)等.今天想跟大家一起研究下事务 ...
- 面试刷题29:mysql事务隔离实现原理?
mysql的事务是innodb存储引擎独有的,myisam存储引擎不支持事务. 事务最经典的例子就是转账了,事务要保证的是一组数据库的操作要么全部成功,要么全部失败.是为了保证高并发场景下数据的正确性 ...
- 【Srping】事务的执行原理(一)
在使用事务的时候需要添加@EnableTransactionManagement注解来开启事务,那么就从@EnableTransactionManagement入手查看一下事务的执行原理. @Enab ...
- 【RocketMQ】事务的实现原理
事务的使用 RocketMQ事务的使用场景 单体架构下的事务 在单体系统的开发过程中,假如某个场景下需要对数据库的多张表进行操作,为了保证数据的一致性,一般会使用事务,将所有的操作全部提交或者在出错的 ...
- 搞懂MySQL InnoDB事务ACID实现原理
前言 说到数据库事务,想到的就是要么都做修改,要么都不做.或者是ACID的概念.其实事务的本质就是锁和并发和重做日志的结合体.那么,这一篇主要讲一下InnoDB中的事务到底是如何实现ACID的. 原子 ...
- RocketMQ源码分析之RocketMQ事务消息实现原理上篇(二阶段提交)
在阅读本文前,若您对RocketMQ技术感兴趣,请加入 RocketMQ技术交流群 根据上文的描述,发送事务消息的入口为: TransactionMQProducer#sendMessageInTra ...
- RocketMQ源码分析之RocketMQ事务消息实现原理中篇----事务消息状态回查
上节已经梳理了RocketMQ发送事务消息的流程(基于二阶段提交),本节将继续深入学习事务状态消息回查,我们知道,第一次提交到消息服务器时消息的主题被替换为RMQ_SYS_TRANS_HALF_TOP ...
- 一文快速搞懂MySQL InnoDB事务ACID实现原理(转)
这一篇主要讲一下 InnoDB 中的事务到底是如何实现 ACID 的: 原子性(atomicity) 一致性(consistency) 隔离性(isolation) 持久性(durability) 隔 ...
随机推荐
- post- build event
Ref:http://blog.csdn.net/teng_ontheway/article/details/8307410 Ref: http://blog.csdn.net/sodickbird/ ...
- noi 1.5 43:质因数分解
描述 已知正整数 n 是两个不同的质数的乘积,试求出较大的那个质数. 输入 输入只有一行,包含一个正整数 n.对于60%的数据,6 ≤ n ≤ 1000.对于100%的数据,6 ≤ n ≤ 2*10^ ...
- 关于sigwait
刚开始看sigwait函数,只是知道它是用来解除阻塞的信号,可是使我疑惑的是那么解除了以后为什么线程收到终止信号SIGINT的时候还是没能终止呢? 于是网上找了一些资料,总的理解如下所示: sig ...
- NSAttributedString字符串属性类
//定义一个可变字符串属性对象aStr NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc]initWithStri ...
- java三大框架
1定义 集成SSH框架的系统从职责上分为四层:表示层.业务逻辑层.数据持久层和域模块层,以帮助开发人员在短期内搭建结构清晰.可复用性好.维护方便的Web应用程序.其中使用Struts作为系统的整体基础 ...
- linux下安装软件出现问题怎么办
是apt-get -f install=apt-get install -f ,是修复依赖关系(depends)的命令,就是假如你的系统上有某个package不满足依赖条件,这个命令就会自动修复,安装 ...
- 【转帖】ActiveX部件不能创建对象的终极解决方案
建一个批处理文件,内容如下: echo 正在修复,这个过程可能需要几分钟,请稍候-- rundll32.exe advpack.dll /DelNodeRunDLL32 %systemroot%Sys ...
- 微信接口php
官方提供的SDK只有一个文本消息功能,我们将所有消息的消息类型及事件响应都整理了进来,并且加入日志记录,代码如下: 更新日志: 2013-01-01 版本1.0,包含Token验证及基本消息接口的收发 ...
- 一周试用yii开发一个带各种该有功能的web程序(三)
接上篇,为什么index 模版里没有任何有关require,inculde类型关键字,却任然有我们认为“多余”的字符出现.因为在至少我的认知里html的结构该是<html><head ...
- HTTP请求 GET与POST是怎么实现?
1.HTTP请求格式: <request line> <headers> <blank line> [<request-body>] 在HTTP请求中, ...