Spring 事务还能这样管理?

开发 架构
在实际开发中,操作数据库时都会涉及到事务管理问题,为此Spring提供了专门用于事务处理的API。Spring的事务管理简化了传统的事务管理流程,并且在一定程度上减少了开发者的工作量。

[[431979]]

本文转载自微信公众号「程序员千羽」,作者程序员千羽。转载本文请联系程序员千羽公众号。

GitHub:https://github.com/nateshao/ssm/tree/master/105-spring-transaction

1.Spring事务管理概述

什么是Spring的事务管理?

在实际开发中,操作数据库时都会涉及到事务管理问题,为此Spring提供了专门用于事务处理的API。Spring的事务管理简化了传统的事务管理流程,并且在一定程度上减少了开发者的工作量。

Spring事务管理的三个核心接口。

在该JAR包的org.springframework.transaction包中,有3个接口文件PlatformTransactionManager、TransactionDefinition和TransactionStatus

事务管理的核心接口

Platform TransactionManager

PlatformTransactionManager接口是Spring提供的平台事务管理器,主要用于管理事务。该接口中提供了三个事务操作的方法,具体如下:

  • TransactionStatus getTransaction(TransactionDefinition definition):用于获取事务状态信息
  • void commit(TransactionStatus status):用于提交事务
  • void rollback(TransactionStatus status):用于回滚事务

PlatformTransactionManager接口只是代表事务管理的接口,并不知道底层是如何管理事务的,具体如何管理事务则由它的实现类来完成。该接口常见的几个实现类如下:

小提示:当底层采用不同的持久层技术时,系统只需使用不同的PlatformTransactionManager实现类即可。

TransactionDefinition

TransactionDefinition接口是事务定义(描述)的对象,该对象中定义了事务规则,并提供了获取事务相关信息的方法,具体如下:

  • String getName( ); 获取事务对象名称
  • int getIsolationLevel( ); 获取事务的隔离级别
  • int getPropagationBehavior( ); 获取事务的传播行为
  • int getTimeout( );获取事务的超时时间
  • boolean isReadOnly( ); 获取事务是否只读

上述方法中,事务的传播行为是指在同一个方法中,不同操作前后所使用的事务。传播行为有很多种,具体如下表所示:

在事务管理过程中,传播行为可以控制是否需要创建事务以及如何创建事务,通常情况下,数据的查询不会影响原数据的改变,所以不需要进行事务管理,而对于数据的插入、更新和删除操作,必须进行事务管理。如果没有指定事务的传播行为,Spring默认传播行为是REQUIRED。

TransactionStatus

TransactionStatus接口是事务的状态,它描述了某一时间点上事务的状态信息。该接口中包含6个方法,具体如下:

  • void flush(); 刷新事务
  • boolean hasSavepoint(); 获取是否存在保存点
  • boolean isCompleted(); 获取事务是否完成
  • boolean isNewTransaction(); 获取是否为新事务
  • boolean isRollbackOnly(); 获取事务是否回滚
  • void setRollbackOnly(); 设置事务回滚

声明式事务管理最大的优点在于开发者无需通过编程的方式来管理事务,只需在配置文件中进行相关的事务规则声明,就可以将事务应用到业务逻辑中。这使得开发人员可以更加专注于核心业务逻辑代码的编写,在一定程度上减少了工作量,提高了开发效率,所以在实际开发中,通常都推荐使用声明式事务管理。

2. 声明式事务管理

如何实现Spring的声明式事务管理?

Spring的声明式事务管理可以通过两种方式来实现, **一种是基于XML的方式,另一种是基于Annotation的方式。**接下来的两个小节中,将对这两种声明式事务管理方式进行详细讲解。

基于XML方式的声明式事务

配置< tx:advice >元素的重点是配置< tx:method >子元素,上图中使用灰色标注的几个属性是< tx:method >元素中的常用属性。其属性描述具体如下:

Account.java

  1. @Data 
  2. public class Account { 
  3.     private Integer id;       // 账户id 
  4.     private String username; // 用户名 
  5.     private Double balance;  // 账户余额 

AccountDao.java

  1. public interface AccountDao { 
  2.     ......... 
  3.     // 转账 
  4.     public void transfer(String outUser,String inUser,Double money); 

AccountDaoImpl.java

  1. @Transactional(propagation = Propagation.REQUIRED, 
  2.             isolation = Isolation.DEFAULT, readOnly = false
  3.     @Override 
  4.     public void transfer(String outUser, String inUser, Double money) { 
  5.         // 收款时,收款用户的余额=现有余额+所汇金额 
  6.         this.jdbcTemplate.update("update account set balance = balance +? " 
  7.                 + "where username = ?",money, inUser); 
  8.         // 模拟系统运行时的突发性问题 
  9. //        int i = 1/0; 
  10.         // 汇款时,汇款用户的余额=现有余额-所汇金额 
  11.         this.jdbcTemplate.update("update account set balance = balance-? " 
  12.                 + "where username = ?",money, outUser); 
  13.     } 

TransactionTest.java

  1. package com.nateshao.jdbc; 
  2.  
  3. import org.junit.jupiter.api.Test; 
  4. import org.springframework.context.ApplicationContext; 
  5. import org.springframework.context.support.ClassPathXmlApplicationContext; 
  6.  
  7. /** 
  8.  * @date Created by 邵桐杰 on 2021/10/15 22:05 
  9.  * @微信公众号 程序员千羽 
  10.  * @个人网站 www.nateshao.cn 
  11.  * @博客 https://nateshao.gitee.io 
  12.  * @GitHub https://github.com/nateshao 
  13.  * @Gitee https://gitee.com/nateshao 
  14.  * Description: 
  15.  */ 
  16. public class TransactionTest { 
  17.      @Test 
  18.     public void xmlTest() { 
  19.         ApplicationContext applicationContext = 
  20.                 new ClassPathXmlApplicationContext("applicationContext.xml"); 
  21.         // 获取AccountDao实例 
  22.         AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao"); 
  23.         // 调用实例中的转账方法 
  24.         accountDao.transfer("千羽""千寻", 100.0); 
  25.         // 输出提示信息 
  26.         System.out.println("转账成功!"); 
  27.     } 

基于Annotation方式的声明式事务

在Spring容器中注册事务注解驱动;

  1. <tx:annotation-driven transaction-manager="transactionManager"/> 

在需要事务管理的类或方法上使用@Transactional注解。

如果将注解添加在Bean类上,则表示事务的设置对整个Bean类的所有方法都起作用;如果将注解添加在Bean类中的某个方法上,则表示事务的设置只对该方法有效。

使用@Transactional注解时,可以通过参数配置事务详情:

applicationContext-annotation.xml

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <beans xmlns="http://www.springframework.org/schema/beans" 
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop" 
  5.     xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xmlns:context="http://www.springframework.org/schema/context" 
  7.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  8.     http://www.springframework.org/schema/beans/spring-beans-4.3.xsd 
  9.     http://www.springframework.org/schema/tx  
  10.     http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 
  11.     http://www.springframework.org/schema/context  
  12.     http://www.springframework.org/schema/context/spring-context-4.3.xsd 
  13.     http://www.springframework.org/schema/aop  
  14.     http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> 
  15.     <!-- 1.配置数据源 --> 
  16.     <bean id="dataSource"  
  17.     class="org.springframework.jdbc.datasource.DriverManagerDataSource"
  18.       <!--数据库驱动 --> 
  19.       <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
  20.       <!--连接数据库的url --> 
  21.       <property name="url" value="jdbc:mysql://localhost/spring?useSSL=false" /> 
  22.       <!--连接数据库的用户名 --> 
  23.       <property name="username" value="root" /> 
  24.       <!--连接数据库的密码 --> 
  25.       <property name="password" value="123456" /> 
  26.    </bean> 
  27.    <!-- 2.配置JDBC模板 --> 
  28.    <bean id="jdbcTemplate"  
  29.             class="org.springframework.jdbc.core.JdbcTemplate"
  30.       <!-- 默认必须使用数据源 --> 
  31.       <property name="dataSource" ref="dataSource" /> 
  32.    </bean> 
  33.    <!--3.定义id为accountDao的Bean --> 
  34.    <bean id="accountDao" class="com.nateshao.jdbc.AccountDaoImpl"
  35.       <!-- 将jdbcTemplate注入到AccountDao实例中 --> 
  36.       <property name="jdbcTemplate" ref="jdbcTemplate" /> 
  37.    </bean> 
  38.    <!-- 4.事务管理器,依赖于数据源 --> 
  39.    <bean id="transactionManager" class= 
  40.      "org.springframework.jdbc.datasource.DataSourceTransactionManager"
  41.       <property name="dataSource" ref="dataSource" /> 
  42.    </bean>     
  43.     <!-- 5.注册事务管理器驱动 --> 
  44.    <tx:annotation-driven transaction-manager="transactionManager"/> 
  45. </beans> 

TransactionTest.java

  1. package com.nateshao.jdbc; 
  2.  
  3. import org.junit.jupiter.api.Test; 
  4. import org.springframework.context.ApplicationContext; 
  5. import org.springframework.context.support.ClassPathXmlApplicationContext; 
  6.  
  7. /** 
  8.  * @date Created by 邵桐杰 on 2021/10/15 22:05 
  9.  * @微信公众号 程序员千羽 
  10.  * @个人网站 www.nateshao.cn 
  11.  * @博客 https://nateshao.gitee.io 
  12.  * @GitHub https://github.com/nateshao 
  13.  * @Gitee https://gitee.com/nateshao 
  14.  * Description: 
  15.  */ 
  16. public class TransactionTest { 
  17.     @Test 
  18.     public void annotationTest() { 
  19.         ApplicationContext applicationContext = 
  20.                 new ClassPathXmlApplicationContext("applicationContext-annotation.xml"); 
  21.         // 获取AccountDao实例 
  22.         AccountDao accountDao = 
  23.                 (AccountDao) applicationContext.getBean("accountDao"); 
  24.         // 调用实例中的转账方法 
  25.         accountDao.transfer("千寻111""千羽111", 100.0); 
  26.         // 输出提示信息 
  27.         System.out.println("转账成功!"); 
  28.     } 
  29.  

总结

本章主要对Spring中的事务管理进行了详细讲解。

  • 首先讲解了Spring事务管理所涉及的3个核心接口,
  • 然后对Spring中事务管理的两种方式进行了介绍,
  • 最后通过案例分别对基于XML方式和基于Annotation方式的声明式事务处理的使用进行了详细讲解。 

通过本章的学习,我相信大家可以对Spring的事务管理知识有一定的了解,并能够掌握Spring声明式事务管理的使用。

 

责任编辑:武晓燕 来源: 程序员千羽
相关推荐

2020-11-16 13:38:31

PostMessage

2021-07-28 06:10:47

拖拽设计器 transmat

2021-09-05 07:55:37

前端Emoji 表情

2012-07-13 11:32:16

网络出口

2020-09-14 11:26:54

BinlogCanal数据库

2009-06-30 16:57:42

Spring事务管理

2023-10-08 08:28:10

Spring事务管理

2009-06-17 14:57:11

Spring事务管理

2014-08-25 09:12:47

Spring事务管理

2009-06-08 17:56:00

SpringJDBC事务

2023-03-27 10:40:09

2009-02-11 11:14:31

事务管理事务开始Spring

2009-02-11 13:08:29

事务提交事务管理Spring

2022-04-11 08:20:36

编程辅助工具GitHubCopilot

2010-03-29 13:34:15

ibmdwSpring

2010-03-23 08:46:40

Spring

2009-09-25 12:59:53

Hibernate事务

2018-12-12 11:30:54

JavaString字符串

2021-04-09 08:23:30

Css前端加载动画

2024-01-30 09:21:29

CSS文字效果文字装饰
点赞
收藏

51CTO技术栈公众号