Mybatis深入之事务管理
最后更新于:2022-04-01 16:30:09
# Mybatis之事务管理
### 简介
Mybatis的事务管理分为两种JdbcTransaction,ManagedTransaction。其中JdbcTransaction仅仅是对数据库连接Connection的一个包装、内部管理数据库事务还是调用Connection的提交、回滚等事务操作方法。ManagedTransaction更直接、什么也没有做。直接将事务交给外部容器管理。
### Mybatis事务管理相关类结构图
类概览:
![类概览](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-08_57a85803ca136.jpg "")
类UML图(典型的简单工厂模式来创建Transaction):
![类UML图](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-08_57a85803dc606.jpg "")
- Transaction 封装事务管理方法的接口
- TransactionFactory 抽象事务工厂生产方法
- JdbcTransactionFactory实现TransactionFactory、用于生产JdbcTransaction的工厂类
- ManagedTransactionFactory实现TransactionFactory、用于生产ManagedTransaction的工厂类
- JdbcTransaction实现Transaction、只是对事务进行了一层包装、实际调用数据库连接Connection的事务管理方法
- ManagedTransaction 实现Transaction没有对数据库连接做任何事务处理、交由外部容器管理
### 源码事务
### 事务配置
Mybatis中关于事务的配置是通过`<transaction type="xx"/>`来指定的。配置如下:
~~~
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
~~~
- type为”JDBC”时、使用JdbcTransaction管理事务。
-
type为”managed”时、使用ManagedTransaction管理事务(也就是交由外部容器管理)
[Mybatis深入之初始化过程 ](http://blog.csdn.net/crave_shy/article/details/46013493 "Mybatis深入之初始化过程")中知道配置文件如何解析的、其中关于事务方面的解析:
~~~
private void environmentsElement(XNode context) throws Exception {
//只关注事务部分...
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
...
}
~~~
~~~
private TransactionFactory transactionManagerElement(XNode context) throws Exception {
if (context != null) {
String type = context.getStringAttribute("type");
Properties props = context.getChildrenAsProperties();
TransactionFactory factory = (TransactionFactory) resolveClass(type).newInstance();
factory.setProperties(props);
return factory;
}
throw new BuilderException("Environment declaration requires a TransactionFactory.");
}
~~~
~~~
typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
~~~
- 重点在于根据type类型判断实例化何种TransactionFactory
- 前面已经知道Mybatis两种事务配置的方式、这里使用的jdbc类型的事务
- 上一篇分析DataSource实例化过程中有一段是关于根据DataSource的type来获取何种Factory的、这里原理同样
- 通过TypeAliasRegistry根据type=’JDBC’来获取TransactionFactory实现类JdbcTransactionFactory
关键在于JdbcTransactionFactory通过newInstance()使用无参构造函数时做了什么工作
~~~
public class JdbcTransactionFactory implements TransactionFactory {
public void setProperties(Properties props) {
}
public Transaction newTransaction(Connection conn) {
return new JdbcTransaction(conn);
}
public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
return new JdbcTransaction(ds, level, autoCommit);
}
}
~~~
- JdbcTransactionFactory默认无参构造方法被调用
- setProperties没有做任何实质性处理
- 对比ManagedTransactionFactory不再贴代码
下面就是获取具有事务特性的数据库连接了
JdbcTransaction:
~~~
public Transaction newTransaction(Connection conn) {
return new JdbcTransaction(conn);
}
~~~
ManagedTransaction:
~~~
public Transaction newTransaction(Connection conn) {
return new ManagedTransaction(conn, closeConnection);
}
~~~
- 两者都是通过Connection来创建具体的实例
JdbcTransaction:
~~~
public class JdbcTransaction implements Transaction {
private static final Log log = LogFactory.getLog(JdbcTransaction.class);
protected Connection connection;
protected DataSource dataSource;
protected TransactionIsolationLevel level;
protected boolean autoCommmit;
public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
dataSource = ds;
level = desiredLevel;
autoCommmit = desiredAutoCommit;
}
public JdbcTransaction(Connection connection) {
this.connection = connection;
}
public Connection getConnection() throws SQLException {
if (connection == null) {
openConnection();
}
return connection;
}
public void commit() throws SQLException {
if (connection != null && !connection.getAutoCommit()) {
if (log.isDebugEnabled()) {
log.debug("Committing JDBC Connection [" + connection + "]");
}
connection.commit();
}
}
public void rollback() throws SQLException {
if (connection != null && !connection.getAutoCommit()) {
if (log.isDebugEnabled()) {
log.debug("Rolling back JDBC Connection [" + connection + "]");
}
connection.rollback();
}
}
public void close() throws SQLException {
if (connection != null) {
resetAutoCommit();
if (log.isDebugEnabled()) {
log.debug("Closing JDBC Connection [" + connection + "]");
}
connection.close();
}
}
protected void setDesiredAutoCommit(boolean desiredAutoCommit) {
try {
if (connection.getAutoCommit() != desiredAutoCommit) {
if (log.isDebugEnabled()) {
log.debug("Setting autocommit to " + desiredAutoCommit + " on JDBC Connection [" + connection + "]");
}
connection.setAutoCommit(desiredAutoCommit);
}
} catch (SQLException e) {
// Only a very poorly implemented driver would fail here,
// and there's not much we can do about that.
throw new TransactionException("Error configuring AutoCommit. "
+ "Your driver may not support getAutoCommit() or setAutoCommit(). "
+ "Requested setting: " + desiredAutoCommit + ". Cause: " + e, e);
}
}
protected void resetAutoCommit() {
try {
if (!connection.getAutoCommit()) {
// MyBatis does not call commit/rollback on a connection if just selects were performed.
// Some databases start transactions with select statements
// and they mandate a commit/rollback before closing the connection.
// A workaround is setting the autocommit to true before closing the connection.
// Sybase throws an exception here.
if (log.isDebugEnabled()) {
log.debug("Resetting autocommit to true on JDBC Connection [" + connection + "]");
}
connection.setAutoCommit(true);
}
} catch (SQLException e) {
log.debug("Error resetting autocommit to true "
+ "before closing the connection. Cause: " + e);
}
}
protected void openConnection() throws SQLException {
if (log.isDebugEnabled()) {
log.debug("Opening JDBC Connection");
}
connection = dataSource.getConnection();
if (level != null) {
connection.setTransactionIsolation(level.getLevel());
}
setDesiredAutoCommit(autoCommmit);
}
}
~~~
- 从源码中可知、JdbcTransaction如何管理事务的、如前面所说调用DataSource事务操作方法。
- 并且对select不进行事务控制
- 当使用DataSource创建数据库连接时、数据库的事务隔离级别使用DataSource默认的事务隔离级别
- 如需指定事务的隔离级别、必须手动创建JdbcTransaction(调用另一个构造函数)
- 关于事务隔离级别会在补充中有
ManagedTransaction:
~~~
public class ManagedTransaction implements Transaction {
private static final Log log = LogFactory.getLog(ManagedTransaction.class);
private DataSource dataSource;
private TransactionIsolationLevel level;
private Connection connection;
private boolean closeConnection;
public ManagedTransaction(Connection connection, boolean closeConnection) {
this.connection = connection;
this.closeConnection = closeConnection;
}
public ManagedTransaction(DataSource ds, TransactionIsolationLevel level, boolean closeConnection) {
this.dataSource = ds;
this.level = level;
this.closeConnection = closeConnection;
}
public Connection getConnection() throws SQLException {
if (this.connection == null) {
openConnection();
}
return this.connection;
}
public void commit() throws SQLException {
// Does nothing
}
public void rollback() throws SQLException {
// Does nothing
}
public void close() throws SQLException {
if (this.closeConnection && this.connection != null) {
if (log.isDebugEnabled()) {
log.debug("Closing JDBC Connection [" + this.connection + "]");
}
this.connection.close();
}
}
protected void openConnection() throws SQLException {
if (log.isDebugEnabled()) {
log.debug("Opening JDBC Connection");
}
this.connection = this.dataSource.getConnection();
if (this.level != null) {
this.connection.setTransactionIsolation(this.level.getLevel());
}
}
}
~~~
- 重点看一下`commit()``rollback()`方法,没有方法体。验证前面其关于事务的管理方式
到这里事务暂时告一段落、一般在使用时会与spring结合、将数据库连接、事务管理都交由spring管理。
### 补充
数据库隔离级别:
先对不同隔离级别涉及到的名词解释:
• 脏读: 对于两个事物 T1, T2, T1 读取了已经被 T2 更新但还没有被提交的字段. 之后, 若 T2 回滚, T1读取的内容就是临时且无效的.
• 不可重复读: 对于两个事物 T1, T2, T1 读取了一个字段, 然后 T2 更新了该字段. 之后, T1再次读取同一个字段, 值就不同了.
• 幻读: 对于两个事物 T1, T2, T1 从一个表中读取了一个字段, 然后 T2 在该表中插入了一些新的行. 之后, 如果 T1 再次读取同一个表, 就会多出几
具体的隔离级别定义:
READ UNCOMMITTED(读未提交数据) 允许事务读取未被其他事务提交的变更,脏读、不可重复读和幻读的问题都会出现
READ COMMITED(读已提交数据) 只允许事务读取已经被其他事务提交的变更,可以避免脏读,但不可重复读和幻读问题仍然会出现
REPEATABLE READ(可重复读) 确保事务可以多次从一个字段中读取相同的值,在这个事务持续期间,禁止其他事务对这个字段进行更新,可以避免脏读和不可重复读,但幻读的问题依然存在
SERIALIZABLE(串行化) 确保事务可以从一个表中读取相同的行,在这个事务持续期间,禁止其他事务对该表执行插入、更新和删除操作,所有并发问题都可以避免,但性能十分低
Oracle 支持的 2 种事务隔离级别:READ COMMITED, SERIALIZABLE. Oracle 默认的事务隔离级别为: READ COMMITED
Mysql 支持 4 中事务隔离级别. Mysql 默认的事务隔离级别为: REPEATABLE READ
更多内容:[Mybatis 目录](http://blog.csdn.net/crave_shy/article/details/45825599)