Spring——事务管理

事务初识

事务是逻辑上的一组操作,要么全部成功,要么全部失败。

事务具有ACID特性,参考百度百科,具体如下:

原子性(Atomicity):整个事务中的所有操作,要么全部完成,要么全部不完成,不可能停滞在中间某个环节。

一致性(Consistency):事务必须始终保持系统处于一致的状态,不管在任何给定的时间并发事务有多少。

隔离性(Isolation):隔离状态执行事务,使它们好像是系统在给定时间内执行的唯一操作。

持久性(Durability):在事务完成以后,该事务对数据库所作的更改便持久的保存在数据库之中,并不会被回滚。

事务操作

1、把事务添加到service层(业务逻辑层)
2、Spring事务管理操作
(1)编程式事务管理
(2)声明式事务管理(主要使用)
3、声明式事务管理
(1)基于注解(主要使用)
(2)基于xml配置文件
4、在spring进行声明式事务管理,底层使用AOP原理
5、Spring事务管理API
(1)提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类
在这里插入图片描述

事务操作(注解声明式事务管理)

bean3.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--开启注解扫描-->
    <context:component-scan base-package="com.gongda.Spring5.Affair"></context:component-scan>

    <!--数据库连接池-->
    <!--destroy-method="close",数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="jdbc:mysql:///test"></property>
        <property name="username" value="root"></property>
        <property name="password" value="password"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    </bean>
    <!--配置JdbcTemplate,注入DataSource-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--创建事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

在service类上面(或者service类里面方法上面)添加事务注解

(1)@Transactional,这个注解添加到类上面,也可以添加方法上面·
(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务
(3)如果把这个注解添加方法上面,为这个方法添加事务

UserService

@Service
@Transactional
public class UserService  {
    @Autowired
    private UserDao userDao;
    //转账方法
    public void accountMoney(){
        userDao.reduceMoney();
        int a=10/0;//用来测试事务
        userDao.addMoney();
    }
}

UserDaoImpl

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void reduceMoney() {
        String sql="update user set usermoney=usermoney-? where userid=?";
        int update = jdbcTemplate.update(sql, 100, 1);
    }

    @Override
    public void addMoney() {
        String sql="update user set usermoney=usermoney+? where userid=?";
        jdbcTemplate.update(sql, 100, 2);
    }
}

TestAffair

  @Test
    public void testAffair(){
        ApplicationContext context=new ClassPathXmlApplicationContext("bean3.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountMoney();

    }

在这里插入图片描述2、事务传播行为
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
3、ioslation:事务隔离级别
(1)在数据库操作中,为了有效保证并发读取数据的正确性,提出的事务隔离级别。如果不考虑隔离性会发生很多问题。
(2)有三个读问题:脏读、不可重复读、幻读(虚读)
(3)脏读:一个未提交的事务读取到了另一个未提交事务的数据。
(4)不可重复读:一个事务进行读取,分别读取到了不同的数据。需要注意的是这里针对的是数据本身,可以理解为针对单笔数据,重点是对数据的修改和删除,所以对行加锁就可以解决。

例如:事务A对数据进行查询,这时事物B开启,对其中一笔数据进行了修改,然后进行了提交(这里进行了提交),然后事务A又对数据进行了查询,发现同一笔不同了,所以事务A读取了两笔不同的数据,两次读取同笔数据有了不同的数据。出现这种根本原因是在事务A进行读操作时,其他事务对数据进行了修改。
(5)幻读(虚读):幻读:一个事务进行读取,分别读取到了不同的数据。需要注意的是这里针对的是数据条数,可以理解为针对多笔数据是个数据集,重点是对数据的新增,所以对表加锁就可以解决。

例如:事务A对数据进行查询,这时事物B开启,对其中一笔数据进行了新增,然后进行了提交(这里进行了提交),然后事务A又对数据进行了查询,发现查询所得的结果集是不一样的。幻读针对的是多笔记录。
不可重复读和幻读的区别:
从总的来看,两者都是对数据进行了两次查询,但两次查询的结果都不一样。
但如果你从控制的角度来看, 两者的区别就比较大
对于前者, 只需要锁住满足条件的记录
对于后者, 要锁住满足条件及其相近的记录

避免不可重复读需要锁行。
避免幻影读则需要锁表。

确实这两者有些相似。但不可重复读重点在于update和delete,而幻读的重点在于insert。

如果使用锁机制来实现这两种隔离级别,在可重复读中,该sql第一次读取到数据后,就将这些数据加锁,其它事务无法修改这些数据,就可以实现可重复 读了。但这种方法却无法锁住insert的数据,所以当事务A先前读取了数据,或者修改了全部数据,事务B还是可以insert数据提交,这时事务A就会 发现莫名其妙多了一条之前没有的数据,这就是幻读,不能通过行锁来避免。需要Serializable隔离级别 ,读用读锁,写用写锁,读锁和写锁互斥,这么做可以有效的避免幻读、不可重复读、脏读等问题,但会极大的降低数据库的并发能力。
所以说不可重复读和幻读最大的区别,就在于如何通过锁机制来解决他们产生的问题。

上文说的,是使用悲观锁机制来处理这两种问题,但是MySQL、ORACLE、PostgreSQL等成熟的数据库,出于性能考虑,都是使用了以乐观锁为理论基础的MVCC(多版本并发控制)来避免这两种问题。

互联网项目一般使用读未提交的隔离级别
(6)通过设置隔离级别(解决读问题)
在这里插入图片描述PEPEATABLE READ:MySQL中默认的隔离级别
在这里插入图片描述
4、timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交则进行回滚
(2)默认值-1,设置时间以秒为单位进行计算
5、readOnly:是否只读
(1)读:查询操作;写:添加、修改、删除操作
(2)readOnly:默认值为false,表示允许添加、修改、删除操作
(3)true:表示不允许添加、修改、删除操作
6、rollbackFor:回滚
设置出现那些异常进行回滚
7、noRollbackFor:不回滚
设置出现那些异常不进行回滚

事务操作(xml声明式事务管理)

1、在spring配置文件中进行配置
(1)配置事务管理器
(2)配置通知
(3)配置切入点和切面

<?xml version="1.0" encoding="UTF-8"?>
<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"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--开启注解扫描-->
    <context:component-scan base-package="com.gongda.Spring5.Affair"></context:component-scan>

    <!--数据库连接池-->
    <!--destroy-method="close",数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用.-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="jdbc:mysql:///test"></property>
        <property name="username" value="root"></property>
        <property name="password" value="password"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    </bean>
    <!--配置JdbcTemplate,注入DataSource-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--第一步:创建事务管理-->
    <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="accountMoney" propagation="REQUIRED"/>
            <!--<tx:method name="account*"/>-->
        </tx:attributes>
    </tx:advice>
    <!--第三步:配置切入点和切面-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="pt" expression="execution(* com.gongda.Spring5.Affair.Service.UserService.*(..))"/>
        <!--配置切面-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"></aop:advisor>
    </aop:config>
</beans>

事务操作(完全注解声明式事务管理)

1、创建配置类,使用配置类替代xml文件
TxConfig

package com.gongda.Spring5.Affair.Config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration//配置类
@ComponentScan(basePackages = "com.gongda.Spring5.Affair")//开启组件扫描
@EnableTransactionManagement//开启事务
public class TxConfig {

    //配置数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///test");
        dataSource.setUsername("root");
        dataSource.setPassword("password");
        return dataSource;
    }

    //创建JdbcTemplate对象
    @Bean
    //在IOC容器中根据类型找到dataSource
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate=new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    @Bean
    //创建事务管理器
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}

TestAffair

@Test
    public void testAffair2(){
        ApplicationContext context=new AnnotationConfigApplicationContext(TxConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountMoney();

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值