《深入理解mybatis原理》 MyBatis事务管理机制
MyBatis作为Java语言的数据库框架,对数据库的事务管理是其很重要的一个方面。本文将讲述MyBatis的事务管理的实现机制。
首先介绍MyBatis的事务Transaction的接口设计以及其不同实现JdbcTransaction
和 ManagedTransaction;接着,从MyBatis的XML配置文件入手。解说MyBatis事务工厂的创建和维护,进而阐述了MyBatis事务的创建和使用;最后分析JdbcTransaction和ManagedTransaction的实现和二者的不同特点。
下面是本文的组织结构:
一、概述
对数据库的事务而言,应该具有下面几点:创建(create)、提交(commit)、回滚(rollback)、关闭(close)。
相应地,MyBatis将事务抽象成了Transaction接口:其接口定义例如以下:
MyBatis的事务管理分为两种形式:
一、使用JDBC的事务管理机制:即利用java.sql.Connection对象完毕对事务的提交(commit())、回滚(rollback())、关闭(close())等
二、使用MANAGED的事务管理机制:这样的机制MyBatis自身不会去实现事务管理,而是让程序的容器如(JBOSS,Weblogic)来实现对事务的管理
这两者的类图例如以下所看到的:
二、事务的配置、创建和使用
1. 事务的配置
我们在使用MyBatis时,通常会在MyBatisXML配置文件里定义类似例如以下的信息:
<environment>节点定义了连接某个数据库的信息。其子节点<transactionManager> 的type 会决定我们用什么类型的事务管理机制。
2.事务工厂的创建
MyBatis事务的创建是交给TransactionFactory 事务工厂来创建的。假设我们将<transactionManager>的type 配置为"JDBC",那么,在MyBatis初始化解析<environment>节点时。会依据type="JDBC"创建一个JdbcTransactionFactory工厂。其源代码例如以下:
/**
* 解析<transactionManager>节点。创建相应的TransactionFactory
* @param context
* @return
* @throws Exception
*/
private TransactionFactory transactionManagerElement(XNode context) throws Exception {
if (context != null) {
String type = context.getStringAttribute("type");
Properties props = context.getChildrenAsProperties();
/*
在Configuration初始化的时候,会通过下面语句。给JDBC和MANAGED相应的工厂类
typeAliasRegistry.registerAlias("JDBC", JdbcTransactionFactory.class);
typeAliasRegistry.registerAlias("MANAGED", ManagedTransactionFactory.class);
下述的resolveClass(type).newInstance()会创建相应的工厂实例
*/
TransactionFactory factory = (TransactionFactory) resolveClass(type).newInstance();
factory.setProperties(props);
return factory;
}
throw new BuilderException("Environment declaration requires a TransactionFactory.");
}如上述代码所看到的,假设type = "JDBC",则MyBatis会创建一个JdbcTransactionFactory.class 实例;假设type="MANAGED",则MyBatis会创建一个MangedTransactionFactory.class实例。
MyBatis对<transactionManager>节点的解析会生成 TransactionFactory实例。而对<dataSource>解析会生成datasouce实例(关于dataSource的解析和原理。读者能够參照我的还有一篇博文:《深入理解mybatis原理》
Mybatis数据源与连接池
),作为<environment>节点,会依据TransactionFactory和DataSource实例创建一个Environment对象,代码例如以下所看到的:private void environmentsElement(XNode context) throws Exception {
if (context != null) {
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
//是和默认的环境同样时,解析之
if (isSpecifiedEnvironment(id)) {
//1.解析<transactionManager>节点,决定创建什么类型的TransactionFactory
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
//2. 创建dataSource
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
DataSource dataSource = dsFactory.getDataSource();
//3. 使用了Environment内置的构造器Builder。传递id 事务工厂TransactionFactory和数据源DataSource
Environment.Builder environmentBuilder = new Environment.Builder(id)
.transactionFactory(txFactory)
.dataSource(dataSource);
configuration.setEnvironment(environmentBuilder.build());
}
}
}
}Environment表示着一个数据库的连接。生成后的Environment对象会被设置到Configuration实例中。以供兴许的使用。
上述一直在讲事务工厂TransactionFactory来创建的Transaction,如今让我们看一下MyBatis中的TransactionFactory的定义吧。
3. 事务工厂TransactionFactory
事务工厂Transaction定义了创建Transaction的两个方法:一个是通过指定的Connection对象创建Transaction。另外是通过数据源DataSource来创建Transaction。与JDBC 和MANAGED两种Transaction相相应,TransactionFactory有两个相应的实现的子类:例如以下所看到的:
4. 事务Transaction的创建
通过事务工厂TransactionFactory非常easy获取到Transaction对象实例。
我们以JdbcTransaction为例,看一下JdbcTransactionFactory是如何生成JdbcTransaction的。代码例如以下:
public class JdbcTransactionFactory implements TransactionFactory { public void setProperties(Properties props) {
} /**
* 依据给定的数据库连接Connection创建Transaction
* @param conn Existing database connection
* @return
*/
public Transaction newTransaction(Connection conn) {
return new JdbcTransaction(conn);
} /**
* 依据DataSource、隔离级别和是否自己主动提交创建Transacion
*
* @param ds
* @param level Desired isolation level
* @param autoCommit Desired autocommit
* @return
*/
public Transaction newTransaction(DataSource ds, TransactionIsolationLevel level, boolean autoCommit) {
return new JdbcTransaction(ds, level, autoCommit);
}
}如上说是,JdbcTransactionFactory会创建JDBC类型的Transaction,即JdbcTransaction。类似地。ManagedTransactionFactory也会创建ManagedTransaction。
以下我们会分别深入JdbcTranaction 和ManagedTransaction,看它们究竟是如何实现事务管理的。
5. JdbcTransaction
JdbcTransaction直接使用JDBC的提交和回滚事务管理机制 。它依赖与从dataSource中取得的连接connection 来管理transaction 的作用域,connection对象的获取被延迟到调用getConnection()方法。假设autocommit设置为on,开启状态的话。它会忽略commit和rollback。
直观地讲,就是JdbcTransaction是使用的java.sql.Connection 上的commit和rollback功能。JdbcTransaction仅仅是相当于对java.sql.Connection事务处理进行了一次包装(wrapper),Transaction的事务管理都是通过java.sql.Connection实现的。JdbcTransaction的代码实现例如以下:
/**
* @see JdbcTransactionFactory
*/
/**
* @author Clinton Begin
*/
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;
} /**
* commit()功能 使用connection的commit()
* @throws SQLException
*/
public void commit() throws SQLException {
if (connection != null && !connection.getAutoCommit()) {
if (log.isDebugEnabled()) {
log.debug("Committing JDBC Connection [" + connection + "]");
}
connection.commit();
}
} /**
* rollback()功能 使用connection的rollback()
* @throws SQLException
*/
public void rollback() throws SQLException {
if (connection != null && !connection.getAutoCommit()) {
if (log.isDebugEnabled()) {
log.debug("Rolling back JDBC Connection [" + connection + "]");
}
connection.rollback();
}
} /**
* close()功能 使用connection的close()
* @throws SQLException
*/
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);
} }6. ManagedTransaction
ManagedTransaction让容器来管理事务Transaction的整个生命周期,意思就是说。使用ManagedTransaction的commit和rollback功能不会对事务有不论什么的影响。它什么都不会做,它将事务管理的权利移交给了容器来实现。看例如以下Managed的实现代码大家就会一目了然:
/**
*
* 让容器管理事务transaction的整个生命周期
* connection的获取延迟到getConnection()方法的调用
* 忽略全部的commit和rollback操作
* 默认情况下。能够关闭一个连接connection,也能够配置它不能够关闭一个连接
* 让容器来管理transaction的整个生命周期
* @see ManagedTransactionFactory
*/
/**
* @author Clinton Begin
*/
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());
}
} }注意:假设我们使用MyBatis构建本地程序。即不是WEB程序,若将type设置成"MANAGED"。那么,我们运行的不论什么update操作,即使我们最后运行了commit操作,数据也不会保留。不会对数据库造成不论什么影响。由于我们将MyBatis配置成了“MANAGED”,即MyBatis自己无论理事务。而我们又是运行的本地程序,没有事务管理功能,所以对数据库的update操作都是无效的。
以上就是 《深入理解mybatis原理》 MyBatis事务管理机制 的所有内容,如有错误或者不准确的地方。请读者指正,共同进步!
-----------------------------------------------------------------------------------------------------------------------------------------
本文源自 http://blog.csdn.net/luanlouis/,如需转载。请注明出处,谢谢。
《深入理解mybatis原理》 MyBatis事务管理机制的更多相关文章
- mybatis深入理解(三)-----MyBatis事务管理机制
MyBatis作为Java语言的数据库框架,对数据库的事务管理是其非常重要的一个方面.本文将讲述MyBatis的事务管理的实现机制.首先介绍MyBatis的事务Transaction的接口设计以及其不 ...
- MyBatis事务管理机制
MyBatis作为Java语言的数据库框架,对数据库的事务管理是其非常重要的一个方面. 本文将讲述MyBatis的事务管理的实现机制,首先介绍MyBatis的事务Transaction的接口设计以 ...
- mybatis事务管理机制详解
1.mybatis事务的配置和使用 mybatis事务有两种使用方式: (a):使用JDBC的事务管理机制:即使用java.Sql.Connection对象完成对事务的提交,回滚和关闭操作. (b): ...
- MyBatis6:MyBatis集成Spring事务管理(下篇)
前言 前一篇文章<MyBatis5:MyBatis集成Spring事务管理(上篇)>复习了MyBatis的基本使用以及使用Spring管理MyBatis的事务的做法,本文的目的是在这个的基 ...
- Spring事务管理机制的实现原理-动态代理
之前在做项目中遇到spring无法进行事务代理问题,最后发现是因为没有写接口,原因当时明白了,看到这篇文章写的清楚些,转过来 我们先来分析一下Spring事务管理机制的实现原理.由于Spring内置A ...
- spring3-spring的事务管理机制
1. Spring的事务管理机制 Spring事务管理高层抽象主要包括3个接口,Spring的事务主要是由他们共同完成的: PlatformTransactionManager:事务管理器—主要用于平 ...
- spring 事务管理机制
1. spring 事务管理抽象 spring 的事务策略机制的核心就是 org.springframework.transaction.PlatformTransactionManager 接口. ...
- Spring入门5.事务管理机制
Spring入门5.事务管理机制 20131126 代码下载 : 链接: http://pan.baidu.com/s/1kYc6c 密码: 233t 回顾之前的知识,Spring 最为核心的两个部分 ...
- Spring入门6事务管理2 基于Annotation方式的声明式事务管理机制
Spring入门6事务管理2 基于Annotation方式的声明式事务管理机制 201311.27 代码下载 链接: http://pan.baidu.com/s/1kYc6c 密码: 233t 前言 ...
随机推荐
- 网页制作之JavaScript部分3--事件及事件传输方式(函数调用 练习题 )重要---持续更新中
一. 事件:说白了就是调用函数的一种方式.它包括:事件源.事件数据.事件处理程序. JS事件 1.js事件通常和函数结合来使用,这样可以通过发生的事件来驱动函数的执行,从而引起html出现不同的效果. ...
- 【ant项目构建学习点滴】--(3)打包及运行jar文件
<?xml version="1.0" encoding="UTF-8"?> <project default="compile&q ...
- [转]linux下iftop工具的安装与使用详解(图文)——实时的网络流量,监控TCP/IP连接(单机)
原文链接:http://www.jbxue.com/LINUXjishu/10735.html 在linux中监控系统资源.进程.内存占用等信息,可以使用top命令.查看网络状态可以使用netstat ...
- 1 #安装php
#安装php #备注:php5..3以后的版本源码不需要打php-fpm补丁,该补丁已经集成进5..3中强制启用fastcgi. [root@dba01 nginx-]# cd [root@dba01 ...
- Jquery学习笔记:删除节点的操作
假设如下的html代码 <div id="mydiv" style="width:100px;height:100px;border:1px solid red&q ...
- Robot Framework与Web界面自动化测试学习笔记:简单例子
假设环境已经搭建好了.这里用RIDE( Robot Framework Test Data Editor)工具来编写用例.下面我们对Robot Framework简称rf. 我们先考虑下一个最基本的登 ...
- BZOJ 2693: jzptab( 莫比乌斯反演 )
速度居然#2...目测是因为我没用long long.. 求∑ lcm(i, j) (1 <= i <= n, 1 <= j <= m) 化简之后就只须求f(x) = x∑u( ...
- ean128与code128 条形码 算法分析
[code128条形码组成] 除终止符(STOP)由13个模块组成外,其他字符均由11个模块组成 就是说,如果用‘1’表示黑线(实模块),用‘0’表示白线(空模块),那么每表示一个字符就需要11条线, ...
- Linux的inode的理解 [转]
Linux的inode的理解 [转] 一.inode是什么? 理解inode,要从文件储存说起. 文件储存在硬盘上,硬盘的最小存储单位叫做"扇区"(Sector).每个扇区储存51 ...
- Charles_N:HTTP请求响应监听工具
Charles:HTTP请求响应监听工具使用说明.doc 1. 介绍 Charles是一个HTTP代理服务器,HTTP监视器,反转代理服务器.它允许一个开发者查看所有连接互联网的HTTP通信 ...