Spring5 事务

1 事务概念

1、事务:事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败。

2、典型场景:银行转账

3、事务四个特性(ACID)
(1)原子性 (要么成功要么失败)
(2)一致性(数据保持一致)
(3)隔离性(互相不干扰)
(4)持久性

2 入门示例

通过银行转账的例子,说明事务的重要性,具体逻辑如下:

img

1、在数据库中建表,添加记录

img

2、创建service,搭建dao,完成对象创建和属性注入

service 注入 dao,在 dao 注入 JdbcTemplate,在 JdbcTemplate 注入 DataSource

3、在dao创建两个方法:多钱和少钱的方法,在service创建转账方法

//service
@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;
    //转账的方法
    public void accountMoney() {
        //lucy 少 100
        userDao.reduceMoney();
        //mary 多 100
        userDao.addMoney();
    }
}

//dao
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //lucy 转账 100 给 mary
    //少钱
    @Override
    public void reduceMoney() {
        String sql = "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql,100,"lucy");
    }
    //多钱
    @Override
    public void addMoney() {
        String sql = "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    } 
}

4、在xml文件中也要弄好组件扫描以及JdbcTemplate对象

<!-- 组件扫描 -->
<context:component-scan base-package="com.atguigu"></context:component-scan>

<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
      destroy-method="close">
    <property name="url" value="jdbc:mysql:///user_db" />
    <property name="username" value="root" />
    <property name="password" value="root" />
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
</bean>

<!-- JdbcTemplate对象 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <!--注入dataSource-->
    <property name="dataSource" ref="dataSource"></property>
</bean>

但是上面的代码中如果业务逻辑层出现有一方错误,代码实现同步不了,会出现一方成功一方失败的现象
所以要使用到事务的架构(需要使用try catch结构,且前三步在try中执行)
具体步骤为

  • 开启事务

  • 进行业务操作

  • 如果没有发生异常提交事务

  • 出现异常的话进行回滚(在catch执行)

3 事务操作

1、事务添加到 JavaEE 三层结构里面Service 层(业务逻辑层)

2、在 Spring 进行事务管理操作有两种方式:编程式事务管理和声明式事务管理(使用)

3、声明式事务管理

(1)基于注解方式(使用)

(2)基于 xml 配置文件方式

4、在 Spring 进行声明式事务管理,底层使用 AOP 原理

5、Spring 事务管理 API

提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类

img

3.1 注解声明式事务管理

1、配置文件配置事务管理器

<!--创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--注入数据源-->
    <property name="dataSource" ref="dataSource"></property>
</bean>

2、开启事务注解

(1)在配置文件引入名称空间tx

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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">

(2)开启事务注解

<!--开启事务注解-->
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

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

@Service
@Transactional
public class UserService {

该注解的参数配置
@Transactional共有以下参数

img

(1)propagation()为传播行为,主要有以下7种
img

所谓的事务方法:对数据库表数据进行变化的操作

img

(2)isolation:事务隔离级别

多事务之间操作如果有隔离不会发生什么事情,但没有隔离会发生以下三种情况:脏读、不可重复读、虚(幻)读

  • 脏读:一个未提交事务读取到另一个未提交事务的数据(事件回滚,导致A读取B还未提交的事务,应该读取原始数据)

img

  • 不可重复读:一个未提交的事务,获取到了一个已经提交修改的事务(A读取B提交的事务,正常来说都提交了才能读取)

img

  • 幻读:一个未提交的数据获取到了另一个事务添加数据

为了防止以上情况,设置事务的隔离性

img

(3)timeout:超时时间

  • 事务需要在一定时间内进行提交,如果不提交进行回滚
  • 默认值是 -1 ,设置时间以秒为单位进行计算

(4)readOnly:是否只读

  • 读:查询操作,写:添加修改删除操作

  • readOnly 默认值 false,表示可以查询,可以添加修改删除操作

  • 设置 readOnly 值是 true,设置成 true 之后,只能查询

(5)rollbackFor:回滚

设置出现哪些异常进行事务回滚

(6)noRollbackFor:不回滚

设置出现哪些异常不进行事务回滚

3.2 xml声明式事务管理

配置文件中进行配置:

  • 配置事务管理器

  • 配置通知-- 增强的部分

  • 配置切入点和切面

<!-- 创建事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--2 配置通知-->
    <tx:advice id="txadvice">
        <!--配置事务参数-->
        <tx:attributes>
            <!--指定哪种规则的方法上面添加事务-->
            <tx:method name="accountMoney" propagation="REQUIRED"/>
            <!--<tx:method name="account*"/>-->
        </tx:attributes>
    </tx:advice>

    <!--3 配置切入点和切面-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="pt" expression="execution(* com.atguigu.spring5.service.UserService.*(..))"/>
        <!--配置切面-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
    </aop:config>

3.3 完全注解声明式事务管理

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

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

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

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

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

测试文件如下:
不是扫描xml文件,而是编译class文件的配置类,通过AnnotationConfigApplicationContext这个类

@Test
public void testAccount2() {

    ApplicationContext context =
            new AnnotationConfigApplicationContext(TxConfig.class);
    UserService userService = context.getBean("userService", UserService.class);
    userService.accountMoney();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦晨涌京

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值