🎨
application-framework
  • Introduction
  • 设计模式篇
    • 设计原则
      • 单一职责原则
      • 里氏替换原则
      • 依赖倒置原则
      • 接口隔离原则
      • 迪米特法则
      • 开闭原则
    • 代理模式
    • 工厂模式
    • 策略模式
    • 等等..设计模式
    • 常用设计模式在开源软件的应用
    • Template设计模式介绍
  • SpringBoot篇
    • SpringBoot官方教程结构图
    • SpringBoot启动过程源码分析
    • SpringBoot启动过程定制化
    • SpringBoot实现自动配置的基础
    • SpringBoot实现自动配置的原理
    • SpringBoot启动类源码分析以及@EnableAutoConfiguration和@SpringBootApplication讲解
    • EnableAutoConfigurationImportSelector 是如何工作的 ?
    • ConfigurationClassParser 是如何工作的 ?
    • SpringBoot源码分析之Spring上下文refresh(重点)
    • SpringBoot中的ApplicationContext - 执行ApplicationContextInitializer初始化器
    • SpringBoot常用配置-Profile
    • Spring Boot API 版本权限控制
  • Mybatis篇
    • Mybatis基础教程
    • Mybatis-Spring基础教程
    • Sqlsession原理
    • Mybatis代码架构分析
    • Mybatis事务
    • Mybatis与Spring集成事务相关问题
    • 结果/参数绑定
    • Mybatis插件拓展/插件原理
    • Mybatis 使用Ehcache缓存机制//自带缓存与Spring结合使用
    • 使用代码生成器快速开发
    • Mybatis使用时的一些注意事项
    • Mybatis配置打印SQL语句
    • 持久层框架mybatis如何防止sql注入
    • SqlSessionTemplate与SqlSessionDaoSupport讲解
    • MapperFactoryBean与MapperScannerConfigurer讲解
    • Spring+MyBatis多数据源配置实现
    • Mybatis与Spring集成事务相关问题
  • Spring源码解读篇
    • Spring 架构图
    • Spring核心结构及组件分析
    • Spring5 Framework体系结构
    • Spring源码剖析
      • BeanFactory
      • BeanPostProcessor源码讲解
      • BeanFactoryPostProcessor源码讲解
      • BeanDefinition源码解析
      • RootBeanDefinition源码解析
      • AnnotatedBeanDefinition源码解析
      • ApplicationContext源码讲解
      • IoC容器的初始化?
      • @Configuration源码讲解
      • Bean的注解(annotation)
      • @ImportSelector、@Import、ImportResource工作原理分析
      • Bean的生命周期
    • IOC机制从设计理念/实现原理到源码解读
    • AOP实现原理
      • aop编程思想
      • aop在Spring中的应用
      • cglib和jdk动态代理
        • java/jdk代理实现与原理详细分析
        • cglib实现动态代理
    • Transaction事务处理源码分析及高级特性
      • 事务概念
      • Spring事务传播
      • 事务隔离级别
      • 事务实现源码分析
      • Spring事物应用实战(一)
      • Spring事务应用实战(二)之spring+hibernate+JTA 分布式事务的例子
    • SpringMVC源码解读
      • DispatcherServlet说明
      • 核心流程剖析及原理分析
      • 请求映射机制
      • 参数绑定与转换机制
      • 页面渲染机制
      • ContextLoader加载过程
      • web.xml 中的listener、 filter、servlet 加载顺序及其详解
      • Spring中WebApplicationContext、DispatcherServlet与web容器的ServletContext关系梳理
    • Spring新版本特性解读
  • JPA篇
    • 简单叙述
    • 基础教程
    • SpringData Jpa、Hibernate、Jpa 三者之间的关系
    • Spring data jpa 全面解析
    • 数据库schema含义
    • 数据库schema与catalog简介
    • Jpa关联映射以及字段映射注解讲解
      • @Entity、@Table、@id
      • @GeneratedValue
      • @Basic、@Column、@Transient
      • @MappedSuperclass、@Embedded、@OrderBy、@Lob、@Data
      • @OneToOne级联配置
      • @OneToMany、@ManyToOne级联配置
      • 更新的同时删除多的一方的旧数据
      • cascade级联属性讲解
      • JpaSpecificationExecutor接口
      • @Query 创建查询
      • @NamedQueries创建查询
      • @CreateDate @LastModifiedDate @EntityListeners、@SQLDelete、@Where
      • 注解关联时报错总结
      • JPA 多对多关联 中间表带有属性 两个外键作为中间表的联合主键时 直接操作中间表查询修改的方法
    • Jpa 使用@Query查询时 (参数可能为空)语句
    • Jpa校验/验证注解
      • Jpa的list校验方式
      • Jpa的基础校验/验证注解
  • Hibernate篇
    • Hibernate基础教程
    • Hibernate主键生成策略
    • Hibernate的体系结构
    • Hibernate面试题
    • 自定义一个方言类——Hibernate Dialect
    • Hibernate 不同数据库的连接及SQL方言
    • Hibernate中一级缓存和二级缓存的具体区别是什么?
    • Hibernate中,对象有三种状态:
Powered by GitBook
On this page
  • TransactionDefinition
  • PlatformTransactionManager

Was this helpful?

  1. Spring源码解读篇
  2. Transaction事务处理源码分析及高级特性

事务实现源码分析

TransactionDefinition

  • 事务的定义接口,包含事务的两个重要属性:传播特性和隔离级别

public interface TransactionDefinition {
    int PROPAGATION_REQUIRED = 0;
    int PROPAGATION_SUPPORTS = 1;
    int PROPAGATION_MANDATORY = 2;
    int PROPAGATION_REQUIRES_NEW = 3;
    int PROPAGATION_NOT_SUPPORTED = 4;
    int PROPAGATION_NEVER = 5;
    int PROPAGATION_NESTED = 6;
    int ISOLATION_DEFAULT = -1;
    int ISOLATION_READ_UNCOMMITTED = 1;
    int ISOLATION_READ_COMMITTED = 2;
    int ISOLATION_REPEATABLE_READ = 4;
    int ISOLATION_SERIALIZABLE = 8;
    int TIMEOUT_DEFAULT = -1;

    int getPropagationBehavior();

    int getIsolationLevel();

    int getTimeout();

    boolean isReadOnly();

    String getName();
}
  • 结构图

  • TransactionDefinition 的一个实现类:DefaultTransactionDefinition

就是对上述属性设置一些默认值,默认的传播特性为PROPAGATION_REQUIRED ,隔离级别为ISOLATION_DEFAULT

public class DefaultTransactionDefinition implements TransactionDefinition, Serializable {
    public static final String PREFIX_PROPAGATION = "PROPAGATION_";
    public static final String PREFIX_ISOLATION = "ISOLATION_";
    public static final String PREFIX_TIMEOUT = "timeout_";
    public static final String READ_ONLY_MARKER = "readOnly";
    static final Constants constants = new Constants(TransactionDefinition.class);
    private int propagationBehavior = 0;//默认值
    private int isolationLevel = -1;
    private int timeout = -1;
    private boolean readOnly = false;
    private String name;

    public DefaultTransactionDefinition() {
    }

    public DefaultTransactionDefinition(TransactionDefinition other) {
        this.propagationBehavior = other.getPropagationBehavior();
        this.isolationLevel = other.getIsolationLevel();
        this.timeout = other.getTimeout();
        this.readOnly = other.isReadOnly();
        this.name = other.getName();
    }

    public DefaultTransactionDefinition(int propagationBehavior) {
        this.propagationBehavior = propagationBehavior;
    }

    public final void setPropagationBehaviorName(String constantName) throws IllegalArgumentException {
        if(constantName != null && constantName.startsWith("PROPAGATION_")) {
            this.setPropagationBehavior(constants.asNumber(constantName).intValue());
        } else {
            throw new IllegalArgumentException("Only propagation constants allowed");
        }
    }

    public final void setPropagationBehavior(int propagationBehavior) {
        if(!constants.getValues("PROPAGATION_").contains(Integer.valueOf(propagationBehavior))) {
            throw new IllegalArgumentException("Only values of propagation constants allowed");
        } else {
            this.propagationBehavior = propagationBehavior;
        }
    }

    public final int getPropagationBehavior() {
        return this.propagationBehavior;
    }

    public final void setIsolationLevelName(String constantName) throws IllegalArgumentException {
        if(constantName != null && constantName.startsWith("ISOLATION_")) {
            this.setIsolationLevel(constants.asNumber(constantName).intValue());
        } else {
            throw new IllegalArgumentException("Only isolation constants allowed");
        }
    }

    public final void setIsolationLevel(int isolationLevel) {
        if(!constants.getValues("ISOLATION_").contains(Integer.valueOf(isolationLevel))) {
            throw new IllegalArgumentException("Only values of isolation constants allowed");
        } else {
            this.isolationLevel = isolationLevel;
        }
    }

    public final int getIsolationLevel() {
        return this.isolationLevel;
    }

    public final void setTimeout(int timeout) {
        if(timeout < -1) {
            throw new IllegalArgumentException("Timeout must be a positive integer or TIMEOUT_DEFAULT");
        } else {
            this.timeout = timeout;
        }
    }

    public final int getTimeout() {
        return this.timeout;
    }

    public final void setReadOnly(boolean readOnly) {
        this.readOnly = readOnly;
    }

    public final boolean isReadOnly() {
        return this.readOnly;
    }

    public final void setName(String name) {
        this.name = name;
    }

    public final String getName() {
        return this.name;
    }

    public boolean equals(Object other) {
        return other instanceof TransactionDefinition && this.toString().equals(other.toString());
    }

    public int hashCode() {
        return this.toString().hashCode();
    }

    public String toString() {
        return this.getDefinitionDescription().toString();
    }

    protected final StringBuilder getDefinitionDescription() {
        StringBuilder result = new StringBuilder();
        result.append(constants.toCode(Integer.valueOf(this.propagationBehavior), "PROPAGATION_"));
        result.append(',');
        result.append(constants.toCode(Integer.valueOf(this.isolationLevel), "ISOLATION_"));
        if(this.timeout != -1) {
            result.append(',');
            result.append("timeout_").append(this.timeout);
        }

        if(this.readOnly) {
            result.append(',');
            result.append("readOnly");
        }

        return result;
    }
}
  • TransactionAttribute接口

public interface TransactionAttribute extends TransactionDefinition {
    String getQualifier();

    boolean rollbackOn(Throwable var1);
}

定义对什么类型的异常进行回滚

  • TransactionAttribute的实现类:DefaultTransactionAttribute

public class DefaultTransactionAttribute extends DefaultTransactionDefinition implements TransactionAttribute {
    private String qualifier;

    public DefaultTransactionAttribute() {
    }

    public DefaultTransactionAttribute(TransactionAttribute other) {
        super(other);
    }

    public DefaultTransactionAttribute(int propagationBehavior) {
        super(propagationBehavior);
    }

    public void setQualifier(String qualifier) {
        this.qualifier = qualifier;
    }

    public String getQualifier() {
        return this.qualifier;
    }

    public boolean rollbackOn(Throwable ex) {//指明了对RuntimeException 和Error进行回滚
        return ex instanceof RuntimeException || ex instanceof Error;
    }

    protected final StringBuilder getAttributeDescription() {
        StringBuilder result = this.getDefinitionDescription();
        if(this.qualifier != null) {
            result.append("; '").append(this.qualifier).append("'");
        }

        return result;
    }
}
  • 事务模板类TransactionTemplate

public class TransactionTemplate extends DefaultTransactionDefinition implements TransactionOperations, InitializingBean {
    protected final Log logger = LogFactory.getLog(this.getClass());
    private PlatformTransactionManager transactionManager;

    public TransactionTemplate() {
    }

    public TransactionTemplate(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public TransactionTemplate(PlatformTransactionManager transactionManager, TransactionDefinition transactionDefinition) {
        super(transactionDefinition);
        this.transactionManager = transactionManager;
    }

    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public PlatformTransactionManager getTransactionManager() {
        return this.transactionManager;
    }

    public void afterPropertiesSet() {
        if (this.transactionManager == null) {
            throw new IllegalArgumentException("Property 'transactionManager' is required");
        }
    }

    public <T> T execute(TransactionCallback<T> action) throws TransactionException {
        if (this.transactionManager instanceof CallbackPreferringPlatformTransactionManager) {
            return ((CallbackPreferringPlatformTransactionManager)this.transactionManager).execute(this, action);
        } else {
            TransactionStatus status = this.transactionManager.getTransaction(this);

            Object result;
            try {
                result = action.doInTransaction(status);
            } catch (RuntimeException var5) {
                this.rollbackOnException(status, var5);
                throw var5;
            } catch (Error var6) {
                this.rollbackOnException(status, var6);
                throw var6;
            } catch (Throwable var7) {
                this.rollbackOnException(status, var7);
                throw new UndeclaredThrowableException(var7, "TransactionCallback threw undeclared checked exception");
            }

            this.transactionManager.commit(status);
            return result;
        }
    }

    private void rollbackOnException(TransactionStatus status, Throwable ex) throws TransactionException {
        this.logger.debug("Initiating transaction rollback on application exception", ex);

        try {
            this.transactionManager.rollback(status);
        } catch (TransactionSystemException var4) {
            this.logger.error("Application exception overridden by rollback exception", ex);
            var4.initApplicationException(ex);
            throw var4;
        } catch (RuntimeException var5) {
            this.logger.error("Application exception overridden by rollback exception", ex);
            throw var5;
        } catch (Error var6) {
            this.logger.error("Application exception overridden by rollback error", ex);
            throw var6;
        }
    }
}

他的核心是里面有PlatformTransactionManager 这个事务管理类,用它来对事务提交和回滚。我们的业务逻辑只要写在TransactionCallback.doInTransaction()方法里面既可以,每次执行这个方法前,先会transactionManager.getTransaction(this)开启一 个事务,执行TransactionCallback.doInTransaction()异常的话会调用transactionManager.rollback(status)来回滚事务,正确的话就会调用transactionManager.commit(status)提交事务;

PlatformTransactionManager

PlatformTransactionManager是spring事务的核心接口。 结构图如下:

接口如下:

public interface PlatformTransactionManager {
    TransactionStatus getTransaction(TransactionDefinition var1) throws TransactionException;

    void commit(TransactionStatus var1) throws TransactionException;

    void rollback(TransactionStatus var1) throws TransactionException;
}
Previous事务隔离级别NextSpring事物应用实战(一)

Last updated 5 years ago

Was this helpful?