从零开始手写 mybatis(四)- mybatis 事务管理机制详解
前景回顾
第一节 从零开始手写 mybatis(一)MVP 版本 中我们实现了一个最基本的可以运行的 mybatis。
第二节 从零开始手写 mybatis(二)mybatis interceptor 插件机制详解
第三节 从零开始手写 mybatis(三)jdbc pool 从零实现数据库连接池
本节我们一起来学习一下 mybatis 中的事务管理。
mybatis 中的事务管理
mybatis 事务有两种使用方式:
使用JDBC的事务管理机制:即使用 java.Sql.Connection对象完成对事务的提交,回滚和关闭操作。
使用MANAGED的事务管理机制:mybatis本身不会去实现事务管理的相关操作,而是交个外部容器来管理事务。当与spring整合使用后,一般使用spring来管理事务。
事务工厂 TransactionFactory
接口定义
这个是对事务的一个工厂,接口如下:
public interface TransactionFactory {
/**
* Sets transaction factory custom properties.
* @param props
*/
void setProperties(Properties props);
/**
* Creates a {@link Transaction} out of an existing connection.
* @param conn Existing database connection
* @return Transaction
* @since 3.1.0
*/
Transaction newTransaction(Connection conn);
/**
* Creates a {@link Transaction} out of a datasource.
* @param dataSource DataSource to take the connection from
* @param level Desired isolation level
* @param autoCommit Desired autocommit
* @return Transaction
* @since 3.1.0
*/
Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit);
}
主要就是如何根据一个 DataSource 创建一个 Transaction。
实际上整体感觉意义不大。
最核心的还是要看一下 Transaction 的实现。
Transaction 接口
public interface Transaction {
/**
* Retrieve inner database connection
* @return DataBase connection
* @throws SQLException
*/
Connection getConnection() throws SQLException;
/**
* Commit inner database connection.
* @throws SQLException
*/
void commit() throws SQLException;
/**
* Rollback inner database connection.
* @throws SQLException
*/
void rollback() throws SQLException;
/**
* Close inner database connection.
* @throws SQLException
*/
void close() throws SQLException;
/**
* Get transaction timeout if set
* @throws SQLException
*/
Integer getTimeout() throws SQLException;
}
这里最核心的实际上只有 commit() 和 rollback(),其他的都是可以忽略的。
针对 getTimeout() 我们就可以为 mybatis 提供一个操作的超时机制。
JdbcTransaction 实现
基于 jdbc 机制的一些处理。
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;
}
@Override
public Connection getConnection() throws SQLException {
if (connection == null) {
openConnection();
}
return connection;
}
@Override
public void commit() throws SQLException {
if (connection != null && !connection.getAutoCommit()) {
if (log.isDebugEnabled()) {
log.debug("Committing JDBC Connection [" + connection + "]");
}
connection.commit();
}
}
@Override
public void rollback() throws SQLException {
if (connection != null && !connection.getAutoCommit()) {
if (log.isDebugEnabled()) {
log.debug("Rolling back JDBC Connection [" + connection + "]");
}
connection.rollback();
}
}
@Override
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) {
if (log.isDebugEnabled()) {
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);
}
@Override
public Integer getTimeout() throws SQLException {
return null;
}
}
这里整体的实现实际上非常简单,就是主动设置了一下自动提交的属性。
ManagedDataSource
这个是另一个实现,实际上更加简单。
commit() 和 rollback() 实现都是空的。
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;
}
@Override
public Connection getConnection() throws SQLException {
if (this.connection == null) {
openConnection();
}
return this.connection;
}
@Override
public void commit() throws SQLException {
// Does nothing
}
@Override
public void rollback() throws SQLException {
// Does nothing
}
@Override
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());
}
}
@Override
public Integer getTimeout() throws SQLException {
return null;
}
}
作用
ManagedTransaction对事务的commit和rollback交给了容器去管理,自己本身并没有做任何处理。
mybatis 的使用方式
如果Mybatis是单独运行的,没有其他框架管理,此时mybatis内部会对下段代码实现。
con.setAutoCommit(false);
//此处命令通知数据库,从此刻开始从当前Connection通道推送而来的
//SQL语句属于同一个业务中这些SQL语句在数据库中应该保存到同一个
//Transaction中.这个Transaction的行为(commit,rollback)由当前Connection管理.
try{
//推送sql语句命令……..;
con.commit();//通知Transaction提交.
}catch(SQLException ex){
con.rollback();//通知Transaction回滚.
}
整体来说这种写法比较原始,我们可以将本来交给 connection 处理的事务,统一调整为使用事务管理器处理。
spring 整合
当然针对 mybatis,大部分都是单个语句的执行。
用于使用 connection 时,实际上得到的是 mybatis 事务管理器封装之后的 connection。
实际上 spring 的整合,可能适用性更强一些。
个人实现
看完了 mybatis 的实现原理之后,我们的实现就变得非常简单。
我们可以简化上面的一些实现,保留核心的部分即可。
接口定义
我们只保留核心的 3 个接口。
/**
* 事务管理
*/
public interface Transaction {
/**
* Retrieve inner database connection
* @return DataBase connection
*/
Connection getConnection();
/**
* Commit inner database connection.
*/
void commit();
/**
* Rollback inner database connection.
*/
void rollback();
}
ManageTransaction
这个实现,我们的 commit 和 rollback 什么都不做。
/**
* 事务管理
*
* @since 0.0.18
*/
public class ManageTransaction implements Transaction {
/**
* 数据信息
* @since 0.0.18
*/
private final DataSource dataSource;
/**
* 隔离级别
* @since 0.0.18
*/
private final TransactionIsolationLevel isolationLevel;
/**
* 连接信息
* @since 0.0.18
*/
private Connection connection;
public ManageTransaction(DataSource dataSource, TransactionIsolationLevel isolationLevel) {
this.dataSource = dataSource;
this.isolationLevel = isolationLevel;
}
public ManageTransaction(DataSource dataSource) {
this(dataSource, TransactionIsolationLevel.READ_COMMITTED);
}
@Override
public Connection getConnection() {
try {
if(this.connection == null) {
Connection connection = dataSource.getConnection();
connection.setTransactionIsolation(isolationLevel.getLevel());
this.connection = connection;
}
return connection;
} catch (SQLException throwables) {
throw new MybatisException(throwables);
}
}
@Override
public void commit() {
//nothing
}
@Override
public void rollback() {
//nothing
}
}
JdbcTransaction.java
这里和上面的相比较,多出了 commit 和 rollback 的逻辑处理。
package com.github.houbb.mybatis.transaction.impl;
import com.github.houbb.mybatis.constant.enums.TransactionIsolationLevel;
import com.github.houbb.mybatis.exception.MybatisException;
import com.github.houbb.mybatis.transaction.Transaction;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 事务管理
*
* @since 0.0.18
*/
public class JdbcTransaction implements Transaction {
/**
* 数据信息
* @since 0.0.18
*/
private final DataSource dataSource;
/**
* 隔离级别
* @since 0.0.18
*/
private final TransactionIsolationLevel isolationLevel;
/**
* 自动提交
* @since 0.0.18
*/
private final boolean autoCommit;
/**
* 连接信息
* @since 0.0.18
*/
private Connection connection;
public JdbcTransaction(DataSource dataSource, TransactionIsolationLevel isolationLevel, boolean autoCommit) {
this.dataSource = dataSource;
this.isolationLevel = isolationLevel;
this.autoCommit = autoCommit;
}
public JdbcTransaction(DataSource dataSource) {
this(dataSource, TransactionIsolationLevel.READ_COMMITTED, true);
}
@Override
public Connection getConnection(){
try {
if(this.connection == null) {
Connection connection = dataSource.getConnection();
connection.setTransactionIsolation(isolationLevel.getLevel());
connection.setAutoCommit(autoCommit);
this.connection = connection;
}
return connection;
} catch (SQLException throwables) {
throw new MybatisException(throwables);
}
}
@Override
public void commit() {
try {
//非自动提交,才执行 commit 操作
if(connection != null && !this.autoCommit) {
connection.commit();
}
} catch (SQLException throwables) {
throw new MybatisException(throwables);
}
}
@Override
public void rollback() {
try {
//非自动提交,才执行 commit 操作
if(connection != null && !this.autoCommit) {
connection.rollback();
}
} catch (SQLException throwables) {
throw new MybatisException(throwables);
}
}
}
从零开始手写 mybatis(四)- mybatis 事务管理机制详解的更多相关文章
- mybatis事务管理机制详解
1.mybatis事务的配置和使用 mybatis事务有两种使用方式: (a):使用JDBC的事务管理机制:即使用java.Sql.Connection对象完成对事务的提交,回滚和关闭操作. (b): ...
- Spring事务管理(详解+实例)
1 初步理解 理解事务之前,先讲一个你日常生活中最常干的事:取钱. 比如你去ATM机取1000块钱,大体有两个步骤:首先输入密码金额,银行卡扣掉1000元钱:然后ATM出1000元钱.这两个步骤必须是 ...
- (转)Spring事务管理(详解+实例)
文章转自:http://blog.csdn.net/trigl/article/details/50968079 写这篇博客之前我首先读了<Spring in action>,之后在网上看 ...
- spring的annotation-driven配置事务管理器详解
http://blog.sina.com.cn/s/blog_8f61307b0100ynfb.html ——————————————————————————————————————————————— ...
- ARC内存管理机制详解
ARC在OC里面个人感觉又是一个高大上的牛词,在前面Objective-C中的内存管理部分提到了ARC内存管理机制,ARC是Automatic Reference Counting---自动引用计数. ...
- object-c(oc)内存管理机制详解
1.内存的创建和释放 让我们以Object-c世界中最最简单的申请内存方式展开,谈谈关于一个对象的生命周期.首先创建一个对象: 1 2 3 //“ClassName”是任何你想写的类名,比如NSStr ...
- Spring事务传播机制详解
1 事务的传播属性(Propagation) 1) REQUIRED ,这个是默认的属性 Support a current transaction, create a new one if none ...
- Android开发——Android 6.0权限管理机制详解
.Android 6.0运行时主动请求权限 3.1 检测和申请权限 下面的例子介绍上面列出的读写SD卡的使用例子,可以使用以下的方式解决: public boolean isGrantExterna ...
- MySQL四种事务隔离级别详解
本文实验的测试环境:Windows 10+cmd+MySQL5.6.36+InnoDB 一.事务的基本要素(ACID) 1.原子性(Atomicity):事务开始后所有操作,要么全部做完,要么全部不做 ...
- MySQL 四种事务隔离级别详解及对比--转
http://www.jb51.net/article/100183.htm 接的隔离级别.它的语法如下: ? 1 SET [SESSION | GLOBAL] TRANSACTION ISOLATI ...
随机推荐
- 问题--C++单例模式中唯一对象初始化时关于在类外调用私有的无参构造问题
1.问题 在单例模式中初始化单例对象Person* Person::signal= new Person; 这一步在类外,而new Person需要调用私有的无参构造,但是只有在类内部才能调用私有函数 ...
- Laravel - 路由的多层嵌套
Route::group(['prefix'=>'admin'],function(){ Route::get('/',function(){ return view('admin.articl ...
- 这一次,弄明白JS中的文件相关(二):HTTP请求头和响应头
(一)前置知识 开始前,我们先来复习一下HTTP的基础知识. HTTP请求分为:请求行.请求头.空行.请求体(也叫正文.请求实体.请求主体). HTTP响应分为:状态行(也叫响应行).响应头.空行.响 ...
- 2.4G+MCU低功耗二合一芯片SI24R03
2.4G+MCU低功耗二合一芯片SI24R03 1 简介 Si24R03 是一款高度集成的低功耗 SOC 芯片,其集成了基于 RISC-V 核的低功耗 MCU 和 工作在 2.4GHz ISM 频段的 ...
- [转帖]Lightning 实操指南
2.2.2 Lightning 实操指南 这一节将介绍如何使用 Lightning 导入数据的实操 2.2.2.1 TiDB Lightning 快速开始 注意 TiDB Lightning 运行后, ...
- [转帖]实战瓶颈定位-我的MySQL为什么压不上去
https://plantegg.github.io/2023/06/20/%E5%AE%9E%E6%88%98%E7%93%B6%E9%A2%88%E5%AE%9A%E4%BD%8D-%E6%88% ...
- [转帖]Linux:CPU频率调节模式以及降频方法简介
概述 cpufreq的核心功能,是通过调整CPU的电压和频率,来兼顾系统的性能和功耗.在不需要高性能时,降低电压和频率,以降低功耗:在需要高性能时,提高电压和频率,以提高性能. cpufreq 是一个 ...
- 【转帖】route命令详解大全(route命令使用实例)
https://www.cxdtop.cn/n/225987.html 在实际的网络应用中,我们可能会遇到这样的网络环境,上外网我们使用的无线网络,内网我们使用的是有限网卡.在设置完成后会出现外网和内 ...
- [转帖]vm内核参数之缓存回收drop_caches
注:本文分析基于3.10.0-693.el7内核版本,即CentOS 7.4 1.关于drop_caches 通常在内存不足时,我们习惯通过echo 3 > /proc/sys/vm/drop_ ...
- [转帖]Linux命令拾遗-top中的%nice是啥
https://www.cnblogs.com/codelogs/p/16060663.html 简介# 这是Linux命令拾遗系列的第八篇,本篇主要介绍top命令中nice%这个指标的含义以及进程优 ...