SpringBoot 中的事务处理

前两章节主要讲解了在SpringBoot中关于对数据的操作,本章节将介绍如何进行事务处理。所有的数据访问技术都离不开事务处理,否则将会造成数据不一致。事务是一系列的动作,一旦其中有一个动作出现错误,必须全部回滚,系统将事务中对数据库的所有已完成的操作全部撤消,滚回到事务开始的状态,避免出现由于数据不一致而导致的接下来一系列的错误。事务的出现是为了确保数据的完整性和一致性,在目前企业级应用开发中,事务管理是必不可少的。

1、SpringBoot事务机制

事务处理机制都会提供API来开启事务、提交事务来完成数据操作,或者在发生错误的时候回滚数据,避免数据的不完整性、不一致性。

SpringBoot事务机制实质上就是Spring的事务机制,是采用统一的机制处理来自不同数据访问技术的事务处理,提供了一个接口 PlatformTransactionManager,已经为不同数据访问技术可以进行不同的实现,如下表。

数据访问技术及实现
数据访问技术 实现类
JDBC DataSourceTransactionManager
JPA JpaTransactionManager
Hibernate HibernateTransactionManager
JDO JdoTransactionManager
分布式事务 JtaTransactionManager

涉及到接口关系如下:

接口PlatformTransactionManager源码如下:

  1. /*

  2. * Copyright 2002-2012 the original author or authors.

  3. *

  4. * Licensed under the Apache License, Version 2.0 (the "License");

  5. * you may not use this file except in compliance with the License.

  6. * You may obtain a copy of the License at

  7. *

  8. * http://www.apache.org/licenses/LICENSE-2.0

  9. *

  10. * Unless required by applicable law or agreed to in writing, software

  11. * distributed under the License is distributed on an "AS IS" BASIS,

  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

  13. * See the License for the specific language governing permissions and

  14. * limitations under the License.

  15. */

  16. package org.springframework.transaction;

  17. import org.springframework.lang.Nullable;

  18. /**

  19. * This is the central interface in Spring's transaction infrastructure.

  20. * Applications can use this directly, but it is not primarily meant as API:

  21. * Typically, applications will work with either TransactionTemplate or

  22. * declarative transaction demarcation through AOP.

  23. *

  24. * <p>For implementors, it is recommended to derive from the provided

  25. * {@link org.springframework.transaction.support.AbstractPlatformTransactionManager}

  26. * class, which pre-implements the defined propagation behavior and takes care

  27. * of transaction synchronization handling. Subclasses have to implement

  28. * template methods for specific states of the underlying transaction,

  29. * for example: begin, suspend, resume, commit.

  30. *

  31. * <p>The default implementations of this strategy interface are

  32. * {@link org.springframework.transaction.jta.JtaTransactionManager} and

  33. * {@link org.springframework.jdbc.datasource.DataSourceTransactionManager},

  34. * which can serve as an implementation guide for other transaction strategies.

  35. *

  36. * @author Rod Johnson

  37. * @author Juergen Hoeller

  38. * @since 16.05.2003

  39. * @see org.springframework.transaction.support.TransactionTemplate

  40. * @see org.springframework.transaction.interceptor.TransactionInterceptor

  41. * @see org.springframework.transaction.interceptor.TransactionProxyFactoryBean

  42. */

  43. public interface PlatformTransactionManager {

  44. /**

  45. * Return a currently active transaction or create a new one, according to

  46. * the specified propagation behavior.

  47. * <p>Note that parameters like isolation level or timeout will only be applied

  48. * to new transactions, and thus be ignored when participating in active ones.

  49. * <p>Furthermore, not all transaction definition settings will be supported

  50. * by every transaction manager: A proper transaction manager implementation

  51. * should throw an exception when unsupported settings are encountered.

  52. * <p>An exception to the above rule is the read-only flag, which should be

  53. * ignored if no explicit read-only mode is supported. Essentially, the

  54. * read-only flag is just a hint for potential optimization.

  55. * @param definition TransactionDefinition instance (can be {@code null} for defaults),

  56. * describing propagation behavior, isolation level, timeout etc.

  57. * @return transaction status object representing the new or current transaction

  58. * @throws TransactionException in case of lookup, creation, or system errors

  59. * @throws IllegalTransactionStateException if the given transaction definition

  60. * cannot be executed (for example, if a currently active transaction is in

  61. * conflict with the specified propagation behavior)

  62. * @see TransactionDefinition#getPropagationBehavior

  63. * @see TransactionDefinition#getIsolationLevel

  64. * @see TransactionDefinition#getTimeout

  65. * @see TransactionDefinition#isReadOnly

  66. */

  67. TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException;

  68. /**

  69. * Commit the given transaction, with regard to its status. If the transaction

  70. * has been marked rollback-only programmatically, perform a rollback.

  71. * <p>If the transaction wasn't a new one, omit the commit for proper

  72. * participation in the surrounding transaction. If a previous transaction

  73. * has been suspended to be able to create a new one, resume the previous

  74. * transaction after committing the new one.

  75. * <p>Note that when the commit call completes, no matter if normally or

  76. * throwing an exception, the transaction must be fully completed and

  77. * cleaned up. No rollback call should be expected in such a case.

  78. * <p>If this method throws an exception other than a TransactionException,

  79. * then some before-commit error caused the commit attempt to fail. For

  80. * example, an O/R Mapping tool might have tried to flush changes to the

  81. * database right before commit, with the resulting DataAccessException

  82. * causing the transaction to fail. The original exception will be

  83. * propagated to the caller of this commit method in such a case.

  84. * @param status object returned by the {@code getTransaction} method

  85. * @throws UnexpectedRollbackException in case of an unexpected rollback

  86. * that the transaction coordinator initiated

  87. * @throws HeuristicCompletionException in case of a transaction failure

  88. * caused by a heuristic decision on the side of the transaction coordinator

  89. * @throws TransactionSystemException in case of commit or system errors

  90. * (typically caused by fundamental resource failures)

  91. * @throws IllegalTransactionStateException if the given transaction

  92. * is already completed (that is, committed or rolled back)

  93. * @see TransactionStatus#setRollbackOnly

  94. */

  95. void commit(TransactionStatus status) throws TransactionException;

  96. /**

  97. * Perform a rollback of the given transaction.

  98. * <p>If the transaction wasn't a new one, just set it rollback-only for proper

  99. * participation in the surrounding transaction. If a previous transaction

  100. * has been suspended to be able to create a new one, resume the previous

  101. * transaction after rolling back the new one.

  102. * <p><b>Do not call rollback on a transaction if commit threw an exception.</b>

  103. * The transaction will already have been completed and cleaned up when commit

  104. * returns, even in case of a commit exception. Consequently, a rollback call

  105. * after commit failure will lead to an IllegalTransactionStateException.

  106. * @param status object returned by the {@code getTransaction} method

  107. * @throws TransactionSystemException in case of rollback or system errors

  108. * (typically caused by fundamental resource failures)

  109. * @throws IllegalTransactionStateException if the given transaction

  110. * is already completed (that is, committed or rolled back)

  111. */

  112. void rollback(TransactionStatus status) throws TransactionException;

  113. }

2、声明式事务

建立在AOP之上的,其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。声明式事务最大的优点就是不需要通过编程的方式管理事务,这样就不需要在业务逻辑代码中掺杂事务管理的代码,只需在配置文件中做相关的事务规则声明(或通过基于@Transactional注解的方式),便可以将事务规则应用到业务逻辑中。

Spring支持声明式事务,被注解的方法在被调用时,Spring开启一个新的事务,当方法无异常结束后,Spring会提交这个事务。

  1. @Transactional

  2. public void insertUser(User user) {

  3. //数据库表的操作

  4. ……

  5. }

注:

(1)@Transactional是来自org.springframework.transaction.annotation包的。

(2)@Transactional不仅可以注解在方法上,也可以注解在类上。当注解在类上时,意味着此类的所有public方法都是开启事务的。如果类级别和方法级别同时使用了@Transactional注解,则使用在类级别的注解会重载方法级别的注解。

以下为注解@Transactional源码:

(为了缩小所占篇数,故去掉注释部分)

  1. package org.springframework.transaction.annotation;

  2. import java.lang.annotation.Documented;

  3. import java.lang.annotation.ElementType;

  4. import java.lang.annotation.Inherited;

  5. import java.lang.annotation.Retention;

  6. import java.lang.annotation.RetentionPolicy;

  7. import java.lang.annotation.Target;

  8. import org.springframework.core.annotation.AliasFor;

  9. import org.springframework.transaction.TransactionDefinition;

  10. @Target({ElementType.METHOD, ElementType.TYPE})

  11. @Retention(RetentionPolicy.RUNTIME)

  12. @Inherited

  13. @Documented

  14. public @interface Transactional {

  15. @AliasFor("transactionManager")

  16. String value() default "";

  17. @AliasFor("value")

  18. String transactionManager() default "";

  19. Propagation propagation() default Propagation.REQUIRED;

  20. Isolation isolation() default Isolation.DEFAULT;

  21. int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;

  22. boolean readOnly() default false;

  23. Class<? extends Throwable>[] rollbackFor() default {};

  24. String[] rollbackForClassName() default {};

  25. Class<? extends Throwable>[] noRollbackFor() default {};

  26. String[] noRollbackForClassName() default {};

  27. }

属性说明如下表:

属性 类型 描述
value String 可选的限定描述符,指定使用的事务管理器
propagation enum: Propagation 定义事务的生命周期,有REQUIRED、SUPPORTS、MANDATORY、REQUIRES_NEW、NOT_SUPPORTED、NEVER、NESTED,详细含义可查阅枚举类org.springframework.transaction.annotation.Propagation源码。
isolation enum: Isolation 可选的事务隔离级别设置,决定了事务的完整性
readOnly boolean 读写或只读事务,默认读写
timeout int (in seconds granularity) 事务超时时间设置
rollbackFor Class对象数组,必须继承自Throwable 导致事务回滚的异常类数组
rollbackForClassName 类名数组,必须继承自Throwable 导致事务回滚的异常类名字数组
noRollbackFor Class对象数组,必须继承自Throwable 不会导致事务回滚的异常类数组
noRollbackForClassName 类名数组,必须继承自Throwable 不会导致事务回滚的异常类名字数组

在SpringBoot中,建议采用注解@Transactional进行事务的控制。

SpringBoot (15)---事务处理相关推荐

  1. 转载:Springboot全局事务处理

    Springboot全局事务处理 本文完全转载:原文为做一只快乐的猴子!的文章:Springboot全局事务处理 只是作为备忘和学习,如有侵权,会删除,谢谢 什么是全局事务 Spring Boot(S ...

  2. [SpringBoot][15][SpringBoot处理高并发]

    第 15 章 SpringBoot处理高并发 在企业实际应用中,会遇到很多高并发场景,最典型的例子就是双十一的抢购.这时候,如果仅仅按照之前简单的方式进行处理,不仅性能无法保证,而且有可能导致数据库某 ...

  3. SpringBoot之事务处理:隔离级别与传播行为

    在Spring中,数据库事务是通过AOP技术来提供服务的.对于声明式事务,是使用@Transactional进行标注的.在@Transactional允许配置许多事物的属性,如事务的隔离级别与传播行为 ...

  4. 【二十六】springboot实现多线程事务处理

     springboot篇章整体栏目:  [一]springboot整合swagger(超详细 [二]springboot整合swagger(自定义)(超详细) [三]springboot整合token ...

  5. Docker 部署SpringBoot项目不香吗?

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者:流星007 链接:toutiao.com/i68433912 ...

  6. docker部署springboot_创建SpringBoot项目部署到docker全过程

    目录 docker 介绍 安装 docker Ubuntu 安装 docker CentOS 安装 docker 通过脚本安装 拉取 java 环境 创建 springboot 项目 打包 sprin ...

  7. HM-SpringBoot1.3【SpringBoot配置】

    1.配置文件分类 1-1 properties 1-2 yml 1-3 yaml 2.yaml 1 server:2 port: 80823 4 5 name: wangwu6 7 #对象8 pers ...

  8. 面试5家公司,我发现这80道面试题最好用,直中要害

    Java集合10题 ArrayList 和 Vector 的区别. 说说 ArrayList,Vector, LinkedList 的存储性能和特性. 快速失败 (fail-fast) 和安全失败 ( ...

  9. Docker 部署不香吗?

    点击上方"朱小厮的博客",选择"设为星标" 后台回复"书",获取 来源:22j.co/ef5f 目录 docker介绍 安装docker U ...

最新文章

  1. LNOI2014 LCA
  2. hdu 4252(单调栈)
  3. mysql如何植入到oracle_MySQL产品的生命周期
  4. 第一篇:Dapper快速学习
  5. 物联网未来发展的十大趋势
  6. java:ToStringBuilder.reflectionToString重写toString
  7. cuda环境安装--windows离线安装
  8. 5.7 矩阵的逆的性质
  9. 2022年熔化焊接与热切割题库
  10. 计算机管理员账户默认密码,win10默认管理员密码,win10管理员初始密码
  11. lisp pl线线段数_编写lisp程序多条多段线连接成一条多段线
  12. Android开发之实时更新系统时间
  13. xx-Pixiv Spider
  14. 深度CTR之AFM:基于Attention网络的FM模型
  15. FTP传输大文件丢包损坏严重,怎么解决?
  16. 在mac上安装md5命令
  17. 数据分析的绩效应该这样来考核
  18. YOLO—神经网络原理
  19. u盘乱码怎么办?看他怎么恢复的(不花一分钱)
  20. JavaScript之jQuery库

热门文章

  1. 机票预定系统类图_出行干货|在法国,廉价机票攻略
  2. 【声学基础】概述——辐射
  3. 汇编的一些坑以及部分上机题目的实现
  4. 滤波电容、去耦电容、旁路电容的作用
  5. 内存的工作原理(一)
  6. 【STM32】HAL库 STM32CubeMX教程十五---FMC-SDRAM(一)
  7. 一文简单理解Java反射及使用
  8. 计算机ip地址无法修改密码,手提电脑怎么修改无线网络的IP地址|无线网络怎么修改密码...
  9. char赋值字符串常量和数值的区别
  10. 5G关键技术研究方向