IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 大数据 -> 07 Spring事务 -> 正文阅读

[大数据]07 Spring事务

目录

一、Spring事务_事务简介

二、Spring事务_事务管理方案

三、Spring事务_事务管理器

四、Spring事务_事务控制的API

五、Spring事务_事务的相关配置

六、Spring事务_事务的传播行为

七、Spring事务_事务的隔离级别

八、Spring事务_注解配置声明式事务

第一种:半注解半配置文件方式

第二种:全注解方式(配置类方式)

九、知识点整理:


一、Spring事务_事务简介

?事务:不可分割的原子操作,即一系列的操作要么同时成功,要么同时失败。

开发过程中,事务管理一般在 service 层, service 层中可能会操作多次数据库,这些操作是不可分割的。否则当程序报错时,可能会造 成数据异常

如:张三给李四转账时,需要两次操作数据库:张三存款减少、李四存款增加。如果这两次数据库操作间出现异常,则会造成数据错误。
项目结构:

?1.准备数据库

CREATE DATABASE `spring` ;
USE `spring`;
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
 ?`id` int(11) NOT NULL AUTO_INCREMENT,
 ?`username` varchar(255) DEFAULT NULL,
 ?`balance` double DEFAULT NULL,
 ?PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT
CHARSET=utf8;
insert ?into
`account`(`id`,`username`,`balance`)
values (1,'张三',1000),(2,'李四',1000);

2.创建Maven项目,引入依赖

<dependencies>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <!--mysql驱动包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!--Aspectj-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.7</version>
        </dependency>

        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.13</version>
        </dependency>
        <!--spring-tx:spring事务-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>

        <!--MyBatis与Spring的整合包,该包可以让Spring创建Mybatis的对象-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.8</version>
        </dependency>

        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!--spring整合junit-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.12.RELEASE</version>
        </dependency>
    </dependencies>

3.创建配置文件applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:comtext="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--   扫描包,为包下的所有类配置扫描包,扫描到该注解才能生效   -->
    <context:component-scan base-package="com.itbaizhan"/>

    <!--  读取配置文件  -->
    <context:property-placeholder location="db.properties"></context:property-placeholder>

    <!--  创建druid连接池数据源对象  -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!--  创建Spring封装过的SqlSessionFactory  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--该对象可以自动扫描持久层接口,并为接口创建代理对象-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--配置扫描的接口包-->
        <property name="basePackage" value="com.itbaizhan.dao"></property>
    </bean>
</beans>

4.在domain层编写实体类Account代码

// 账户
public class Account {
 ? ?private int id; // 账号
 ? ?private String username; // 用户名
 ? ?private double balance; // 余额
 ? ?
 ? ?// 省略getter/setter/tostring/构造方法
}

5.在dao层编写AccountDao接口

@Repository
public interface AccountDao {
//      根据id查找用户
    @Select("select * from account where id = #{id} ")
    Account findById(int id);

//      修改用户
    @Update("update account set balance = #{balance} where id = #{id} ")
    void update(Account account);
}

6.在service层编写AccountService类

@Service("accountService")
public class AccountService {
    @Autowired
    private AccountDao accountDao;

    /**
     * 转账
     * @param id1     转出人id
     * @param id2     转入人id
     * @param price    金额
     */
    public void transfer(int id1,int id2,double price){
//        转出人减少余额
        Account account1 = accountDao.findById(id1);
        account1.setBalance(account1.getBalance()-price);
        accountDao.update(account1);

        int i = 1/0;//设置异常,模拟程序出错

//        转入人增加金额
        Account account2 = accountDao.findById(id2);
        account2.setBalance(account2.getBalance()+price);
        accountDao.update(account2);
    }
}

7.测试转账

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class serviceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer(){
        accountService.transfer(1,2,500);
    }
}
8.测试结果:
程序执行了异常前面的代码,异常后面的代码没有执行,此时没有事务管理,会造成张三的余额减少,而李四的余额并没有增加。所以事务处理位于业务层,即一个service 方法是不能分割的。

二、Spring事务_事务管理方案

?service层手动添加事务可以解决该问题:

@Service("accountService")
public class AccountService {
    @Autowired
    private AccountDao accountDao;

    /**
     * 转账
     * @param id1     转出人id
     * @param id2     转入人id
     * @param price    金额
     */
    public void transfer(int id1,int id2,double price){
     try{
            //        转出人减少余额
        Account account1 = accountDao.findById(id1);
        account1.setBalance(account1.getBalance()-price);
        accountDao.update(account1);

        int i = 1/0;//设置异常,模拟程序出错

//        转入人增加金额
        Account account2 = accountDao.findById(id2);
        account2.setBalance(account2.getBalance()+price);
        accountDao.update(account2);
            sqlSession.commit();
        }catch(Exception e){
            sqlSession.rollback();
         }

    }
}
但在 Spring 管理下不允许手动提交和回滚事务。此时我们需要使用Spring的事务管理方案,在 Spring 框架中提供了两种事务管理方案:
1. ? 编程式事务:通过编写代码实现事务管理。
2.声明式事务:基于AOP技术实现事务管理。
Spring框架中,编程式事务管理很少使用,我们对声明式事务管理进行详细学习。
Spring的声明式事务管理在底层采用了AOP 技术,其最大的优点在于无需通过编程的方式管理事务,只需要在配置文件中进行相关的规则声明,就可以将事务规则应用到业务逻辑中
使用AOP技术为service方法添加如下通知:

三、Spring事务_事务管理器

?Spring依赖事务管理器进行事务管理,事务管理器即一个通知类,我们为该通知类设置切点为service层方法即可完成事务自动管理。由于不同技术操作数据库,进行事务操作的方法不同。如:JDBC提交事务是 connection.commit() MyBatis提交事务是 sqlSession.commit() ,所以Spring提供了多个事务管理器。

事务管理器名称作用
org.springframework.jdbc.datasource.DataSourceTransactionManager针对JDBC技术提供的事务管理器,适用于JDBC和MyBatis
org.springframework.orm.hibernate3.HibernateTransactionManger针对于Hibernate框架提供的事务管理器。适用于Hibernate
org.springframework.orm.jpa.JpaTransactionManger针对于JPA技术提供的事务管理器。适用于JPA
org.springframework.transaction.jta.JtaTransactionManger跨越了多个事务管理源。适用在两个或者多个不同的数据源中实现事务控制。

?我们使理。

?1.引入依赖

<!-- 事务管理 -->
<dependency>
 ? ?<groupId>org.springframework</groupId>
 ? ?<artifactId>spring-tx</artifactId>
 ? ?<version>5.3.13</version>
</dependency>
<!-- AspectJ -->
<dependency>
 ? ?<groupId>org.aspectj</groupId>
 ? ?<artifactId>aspectjweaver</artifactId>
 ? ?<version>1.8.7</version>
</dependency>

2.在配置文件中引入约束

xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd

3.进行事务配置

    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--进行事务相关配置-->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <!--暂时所有方法都使用默认配置   事务隔离级别设置为默认会使用数据库默认隔离级别-->
            <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"/>
            <!--查询方法是只读事务   查询方法的隔离级别可以设置低一点,因为不涉及事务操作-->
            <tx:method name="find*" read-only="true" isolation="READ_UNCOMMITTED"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!--配置切面-->
    <aop:config>
        <!--配置切点-->
        <aop:pointcut id="pointcut" expression="execution(* com.itbaizhan.service.*.*(..))"/>
        <!--配置通知-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
    </aop:config>

配置好Spring事务之后,这是再执行上面的“张三李四转账”操作,要么全部执行,要么全部不执行。

四、Spring事务_事务控制的API

?Spring进行事务控制的功能是由三个接口提供的这三个接口是Spring实现的,在开发中我们很少使用到,只需要了解他们的作用即可:

PlatformTransactionManager 接口
PlatformTransactionManager Spring 提供的事务管理器接口,所有事务管理器都实现了该接口
该接口中提供了三个事务操作方法:
TransactionStatus getTransactionTransactionDefinition definition ):获取事务状态信息。
void commitTransactionStatus status ):事务提交
void rollbackTransactionStatus status ):事务回滚
TransactionDefinition 接口
TransactionDefinition是事务的定义信息对象, 它有如下方法:
String getName() 获取事务对象名称。
int getIsolationLevel() 获取事务的隔离级别。
int getPropagationBehavior() 获取事务的传播行为。
int getTimeout() 获取事务的超时时间。
boolean isReadOnly() 获取事务是否只读。
TransactionStatus 接口
TransactionStatus 是事务的状态接口,它描述了某一时间点上事务的状态信息。它有如下方法:
void flush() : 刷新事务
boolean hasSavepoint() : 获取是否存在保存点
boolean isCompleted():? 获取事务是否完成
boolean isNewTransaction():? 获取是否是新事务
boolean isRollbackOnly():? 获取是否回滚
void setRollbackOnly() : 设置事务回滚

五、Spring事务_事务的相关配置

<tx:advice> 中可以进行事务的相关配置:
<!--进行事务相关配置-->
    <tx:advice id="txAdvice">
        <tx:attributes>
            <!--暂时所有方法都使用默认配置   事务隔离级别设置为默认会使用数据库默认隔离级别-->
            <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"/>
            <!--查询方法是只读事务   查询方法的隔离级别可以设置低一点,因为不涉及事务操作-->
            <tx:method name="find*" read-only="true" isolation="READ_UNCOMMITTED"></tx:method>
        </tx:attributes>
    </tx:advice>
<tx:method> 中的属性:
name :指定配置的方法。 * 表示所有方法, find* 表示所有以 find 开头的方法。
read-only :是否是只读事务,只读事务不存在数据的修改,数据库将会为只读事务提供一些
优化手段,会对性能有一定提升,建议在查询中开启只读事务。
timeout :指定超时时间,在限定的时间内不能完成所有操作就会抛异常。默认永不超时(一般不配置)
rollback-for:指定某个异常事务回滚,其他异常不回滚。默认所有异常回滚。(一般不配置)
no-rollback-for :指定某个异常不回滚,其他异常回滚。默认所有异常回滚。(一般不配置)
propagation :事务的传播行为
isolation :事务的隔离级别

六、Spring事务_事务的传播行为

?事务传播行为是指多个含有事务的方法相互调用时,事务如何在这些方法间传播。

如果在 service 层的方法中调用了其他的 service 方法,假设每次执行service方法都要开启事务,此时就无法保证外层方法和内层方法处于同一个事务当中。
// method1的所有方法在同一个事务中
public void method1(){
 ? ?// 此时会开启一个新事务,这就无法保证method1()
中所有的代码是在同一个事务中
 ? ?method2();
 ? ?System.out.println("method1");
}
public void method2(){
 ? ?System.out.println("method2");
}
事务的传播特性就是解决这个问题的,Spring帮助我们将外层方法和内层方法放入同一事务中。
传播行为介绍
REQUIRED
默认。支持当前事务,如果当前没有事务,就新建一个事务这是最常见的选择。
SUPPORTS
支持当前事务,如果当前没有事务,就以非事务方式执行。
MANDATORY
支持当前事务,如果当前没有事务,就抛出异常。
REQUIRES_NEW
新建事务,如果当前存在事务,把当前事务挂起。
NOT_SUPPORTED
以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
NEVER
以非事务方式执行,如果当前存在事务,则抛出异常。
NESTED
必须在事务状态下执行,如果没有事务则新建事务,如果当前有事务则创建一个嵌套事务

七、Spring事务_事务的隔离级别

?事务隔离级别反映事务提交并发访问时的处理态度,隔离级别越高,数据出问题的可能性越低,但效率也会越低。

隔离级别脏读不可重复读幻读
READ_UNCOMMITED (读取未提交内容)
READ_COMMITED (读取提交内容)
×
REPEATABLE_READ (重复读)
××
SERIALIZABLE (可串行化)
×××

√表示有,×表示没有

如果设置为DEFAULT会使用数据库的默认隔离级别。
SqlServer , Oracle 默认的事务隔离级别是 READ_COMMITED
Mysql 的默认隔离级别是 REPEATABLE_READ

八、Spring事务_注解配置声明式事务

Spring支持使用注解配置声明式事务。用法如下:

第一种:半注解半配置文件方式

1.在配置文件applicationContext.xml中注册事务注解驱动

   <!--注册事务注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

2.在需要事务支持的方法或类上加@Transactional注解

@Service("accountService")
//@Transactional:作用于类上时,该类的所有public方法都将具有该类型的事务属性
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
public class AccountService {
    @Autowired
    private AccountDao accountDao;

    /**
     * 转账
     * @param id1     转出人id
     * @param id2     转入人id
     * @param price    金额
     */
    public void transfer(int id1,int id2,double price){
//        转出人减少余额
        Account account1 = accountDao.findById(id1);
        account1.setBalance(account1.getBalance()-price);
        accountDao.update(account1);

        int i = 1/0;//设置异常,使得操作中断,造成事务问题

//        转入人增加金额
        Account account2 = accountDao.findById(id2);
        account2.setBalance(account2.getBalance()+price);
        accountDao.update(account2);
    }

    //作用于方法上时,该方法将都具有该类型的事务属性
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)
    public Account findById(int id){
        return accountDao.findById(id);
    }
}

测试方法:

@RunWith(SpringJUnit4ClassRunner.class)
//加载配置文件
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class serviceTest {
    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer(){
        accountService.transfer(1,2,500);
    }
}

第二种:全注解方式(配置类方式)

配置类代替xml中的注解事务支持:在配置类上方写 @EnableTranscationManagement
@Configuration//表名配置类
@ComponentScan("com.itbaizhan")//扫描注解
@EnableTransactionManagement//开启注解事务
public class SpringConfig {
//    创建druid连接池数据源对象
    @Bean
    public DataSource getDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql:///spring");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("123456");
        return druidDataSource;
    }

    @Bean
    public SqlSessionFactoryBean getSqlSession(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer getMapperScanner(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.itbaizhan.dao");
        return mapperScannerConfigurer;
    }

    @Bean
    public DataSourceTransactionManager getTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}

测试方法:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)//加载配置类
public class serviceTest2 {
    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer(){
        accountService.transfer(1,2,500);
    }
}

九、知识点整理:

1.事务指“不可分割的原子操作,要么全部执行,要么全部不执行”。

2.Spring声明式事务在底层采用了AOP技术

3.DataSourceTransactionManager 可以管理MyBatis的事务

4.Spring中,所有的事务管理器都实现了"PlatformTransactionManager 接口

5.<tx:method> read-only 属性配置只读事务,isolation属性配置隔离级别

6..Spring中,事务的默认传播级别为REQUIRED

7.事务的隔离级别越高,数据出问题的可能性越低,效率也会越低。

8.Spring中,配置声明式事务用到的注解为@Transactional

  大数据 最新文章
实现Kafka至少消费一次
亚马逊云科技:还在苦于ETL?Zero ETL的时代
初探MapReduce
【SpringBoot框架篇】32.基于注解+redis实现
Elasticsearch:如何减少 Elasticsearch 集
Go redis操作
Redis面试题
专题五 Redis高并发场景
基于GBase8s和Calcite的多数据源查询
Redis——底层数据结构原理
上一篇文章      下一篇文章      查看所有文章
加:2022-08-06 10:50:33  更:2022-08-06 10:50:59 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 22:20:36-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码