一、Mybatis事务(二)事务隔离级别

二、Mybatis事务(三)事务工厂

Mybatis管理事务是分为两种方式:

(1)使用JDBC的事务管理机制,就是利用java.sql.Connection对象完成对事务的提交
(2)使用MANAGED的事务管理机制,这种机制mybatis自身不会去实现事务管理,而是让程序的容器(JBOSS,WebLogic)来实现对事务的管理
在Mybatis的配置文件中可以配置事务管理方式如下:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><environments default="development"><environment id="development"><!--配置事务的管理方式--><transactionManager type="JDBC" /><!-- 配置数据库连接信息 --><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/mybatis" /><property name="username" value="root" /><property name="password" value="XDP" /></dataSource></environment></environments>    </configuration>

Mybatis提供了一个事务接口Transaction,以及两个实现类jdbcTransaction和ManagedTransaction,当spring与Mybatis一起使用时,spring提供了一个实现类SpringManagedTransaction
Transaction接口:提供的抽象方法有获取数据库连接getConnection,提交事务commit,回滚事务rollback和关闭连接close,源码如下:

 //事务接口
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;}

JdbcTransaction实现类:Transaction的实现类,通过使用jdbc提供的方式来管理事务,通过Connection提供的事务管理方法来进行事务管理,源码如下:

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;}@Overridepublic Connection getConnection() throws SQLException {if (connection == null) {openConnection();}//返回连接return connection;}@Overridepublic void commit() throws SQLException {if (connection != null && !connection.getAutoCommit()) {if (log.isDebugEnabled()) {log.debug("Committing JDBC Connection [" + connection + "]");}//连接提交connection.commit();}}@Overridepublic void rollback() throws SQLException {if (connection != null && !connection.getAutoCommit()) {if (log.isDebugEnabled()) {log.debug("Rolling back JDBC Connection [" + connection + "]");}//连接回滚connection.rollback();}}@Overridepublic 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. select操作没有commit和rollback事务// Some databases start transactions with select statements 一些数据库在select操作是会开启事务// 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);}}

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;}@Overridepublic Connection getConnection() throws SQLException {if (this.connection == null) {openConnection();}return this.connection;}//提交操作无效@Overridepublic void commit() throws SQLException {// Does nothing}//回滚操作无效@Overridepublic void rollback() throws SQLException {// Does nothing}@Overridepublic 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());}}}

SpringManagedTransaction实现类:它其实也是通过使用JDBC来进行事务管理的,当spring的事务管理有效时,不需要操作commit/rollback/close,spring事务管理会自动帮我们完成,源码如下:

public class SpringManagedTransaction implements Transaction {private static final Log LOGGER = LogFactory.getLog(SpringManagedTransaction.class);private final DataSource dataSource;private Connection connection;private boolean isConnectionTransactional;private boolean autoCommit;//获得数据源public SpringManagedTransaction(DataSource dataSource) {notNull(dataSource, "No DataSource specified");this.dataSource = dataSource;}/*** {@inheritDoc}* 返回数据库连接*/@Overridepublic Connection getConnection() throws SQLException {if (this.connection == null) {openConnection();}return this.connection;}/*** Gets a connection from Spring transaction manager and discovers if this* {@code Transaction} should manage connection or let it to Spring.* <p>* It also reads autocommit setting because when using Spring Transaction MyBatis* thinks that autocommit is always false and will always call commit/rollback* so we need to no-op that calls.*从spring的事务管理中获得一个连接 */private void openConnection() throws SQLException {this.connection = DataSourceUtils.getConnection(this.dataSource);this.autoCommit = this.connection.getAutoCommit();this.isConnectionTransactional = DataSourceUtils.isConnectionTransactional(this.connection, this.dataSource);if (LOGGER.isDebugEnabled()) {LOGGER.debug("JDBC Connection ["+ this.connection+ "] will"+ (this.isConnectionTransactional ? " " : " not ")+ "be managed by Spring");}}/*** {@inheritDoc}*/@Overridepublic void commit() throws SQLException {if (this.connection != null && !this.isConnectionTransactional && !this.autoCommit) {if (LOGGER.isDebugEnabled()) {LOGGER.debug("Committing JDBC Connection [" + this.connection + "]");}this.connection.commit();}}/*** {@inheritDoc}*/@Overridepublic void rollback() throws SQLException {if (this.connection != null && !this.isConnectionTransactional && !this.autoCommit) {if (LOGGER.isDebugEnabled()) {LOGGER.debug("Rolling back JDBC Connection [" + this.connection + "]");}this.connection.rollback();}}/*** {@inheritDoc}*/@Overridepublic void close() throws SQLException {DataSourceUtils.releaseConnection(this.connection, this.dataSource);}}

Mybatis的事务管理机制还是比较简单的,其并没有做过多的操作,只是封装一下方便别人调用而已。

Mybatis事务(一)事务管理方式相关推荐

  1. Spring不同事务管理方式与声明式事务管理局部回滚处理方案

    Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource.TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分.  DataS ...

  2. Spring事务管理详解_基本原理_事务管理方式

    Spring事务管理详解_基本原理_事务管理方式 1. 事务的基本原理 Spring事务的本质其实就是数据库对事务的支持,使用JDBC的事务管理机制,就是利用java.sql.Connection对象 ...

  3. [JAVAEE]实验06:基于XML和基于注解的声明式事务管理方式模拟银行转账程序

    一.实验目的: 熟练掌握声明式事务管理. 二.实验内容: 编写一个模拟银行转账的程序,要求在转账时通过Spring对事务进行控制. 三.实验要求: 分别使用基于XML和基于注解的声明式事务管理方式来实 ...

  4. spring(三)之事务、事务管理器(TransactionManager)简介及实现事务的4种方式

    1.事务 一组业务ACID操作,要么全部成功,要么全部不成功. 事务特性:①原子性,针对整体而言(一个事务不可以被拆分):②一致性,针对数据而言(一个事务执行之前和执行之后必须处于一致性状态,一个事务 ...

  5. MyBatis及Spring事务初学总结

    MyBatis是从iBatis项目继承而来,是目前互联网公司的主流数据访问层框架. 在实际使用中与Spring一起使用.MyBatis出了MyBatis-Spring组件,用于两者之间的整合,使用Sp ...

  6. Mybatis 中的事务

    1. Mybaits中的事务接口Transaction public interface Transaction {Connection getConnection() throws SQLExcep ...

  7. Spring-09 整合mybatis声明式事务

    声明式事务 回顾事务 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性. 事务就是把一系列的动作当成一个独立的工作单 ...

  8. Insight Mybatis JdbcTemplate 混合事务控制的实现

    混合使用的背景 最近项目中需要引入工作流引擎,实现业务和流程设计.流转的解耦. 工作流流引擎选用的是snaker,轻量.易上手.可定制.访问数据库用的是JdbcTemplate . 项目中原有的持久层 ...

  9. 多表查询事务DCL权限管理

    多表查询: * 查询语法:select列名列表from表名列表where.... * 准备sql# 创建部门表CREATE TABLE dept(id INT PRIMARY KEY AUTO_INC ...

最新文章

  1. 【synchronized底层原理之4】锁的升级过程及比较
  2. 手机python软件怎么创建项目_pycharm怎么创建项目
  3. 知乎上砍手豪关于kaggle的观点(转载)
  4. mysql 单表字段多少合适_复制信息记录表|全方位认识 mysql 系统库
  5. 阿里云java mysql环境_阿里云搭建centos java mysql nginx环境
  6. 持续狂奔的拼多多快追上阿里了
  7. openwrt打印机支持列表_共享打印机的三种安装连接方法
  8. Service worker 的概念和用法
  9. python ide_Python id()
  10. TG Pro for mac电脑温度管理工具
  11. 【Vue: 使用pdf.js顯示PDF Viewer】
  12. 考研计算机专业流程,计算机专业考研复试基本流程-文都教育.doc
  13. 设计模式——装饰模式Decorate
  14. visual stadio code(VS code) 中 Markdown简明操作[持续更新]
  15. 计算机内部常用的计数形式,公务员考试计算机类专业
  16. 嫦娥奔月-第13届蓝桥杯Scratch选拔赛真题精选
  17. 工程图学及计算机绘图宋卫卫,工程图学及计算机绘图习题集
  18. 这才叫大数据!腾讯首次公布微信数据(完整版)
  19. ENVI使用教程之直方图
  20. 惊云下载系统偷天空避免产生链接来自天空软件站的信息程序

热门文章

  1. 理解了DirectShow播放原理
  2. Windows文件操作XCOPY命令的使用方法及参数详解
  3. GRBL 软件:简单解释的基础知识
  4. 效率高到爆炸的IT运维软件您安装了吗?
  5. Java获取url地址图片
  6. js mysql orm_nodejs ORM框架对比
  7. 全栈Python 编程必备
  8. 2021年度十大开源SLAM算法
  9. 软件测试工程师 | 不拼学历,还能进大厂吗?
  10. 邮储银行年薪可以达到多少,你了解吗?