1. 概述
MyBatis 对数据库中的事务进行了抽象,其自身提供了相应的事务接口和简单实现。
在很多场景中,MyBatis 会与 Spring 框架集成,并由 Spring 框架管理事务
2. Transaction
org.apache.ibatis.transaction.Transaction ,事务接口。代码如下:
public interface Transaction {
/**
* Retrieve inner database connection.
* @return DataBase connection
* @throws SQLException
* the SQL exception
*/
Connection getConnection() throws SQLException;
/**
* Commit inner database connection.
* @throws SQLException
* the SQL exception
*/
void commit() throws SQLException;
/**
* Rollback inner database connection.
* @throws SQLException
* the SQL exception
*/
void rollback() throws SQLException;
/**
* Close inner database connection.
* @throws SQLException
* the SQL exception
*/
void close() throws SQLException;
/**
* Get transaction timeout if set.
*
* @return the timeout
* @throws SQLException
* the SQL exception
*/
Integer getTimeout() throws SQLException;
}
2.1 JdbcTransaction
org.apache.ibatis.transaction.jdbc.JdbcTransaction ,实现 Transaction 接口,基于 JDBC 的事务实现类。代码如下:
// JdbcTransaction.java
public class JdbcTransaction implements Transaction {
private static final Log log = LogFactory.getLog(JdbcTransaction.class);
/**
* Connection 对象
*/
protected Connection connection;
/**
* DataSource 对象
*/
protected DataSource dataSource;
/**
* 事务隔离级别
*/
protected TransactionIsolationLevel level;
/**
* 是否自动提交
*/
protected boolean autoCommit;
public JdbcTransaction(DataSource ds, TransactionIsolationLevel desiredLevel, boolean desiredAutoCommit) {
dataSource = ds;
level = desiredLevel;
autoCommit = desiredAutoCommit;
}
public JdbcTransaction(Connection connection) {
this.connection = connection;
}
@Override
public Connection getConnection() throws SQLException {
// 连接为空,进行创建
if (connection == null) {
openConnection();
}
return connection;
}
&