1 事务概念

1、事务:事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败。
2、典型场景:银行转账
3、事务四个特性(ACID)
(1)原子性 (要么成功要么失败)
(2)一致性(数据保持一致)
(3)隔离性(互相不干扰)
(4)持久性

2 入门示例

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

1、在数据库中建表,添加记录
image.png
2、创建service,搭建dao,完成对象创建和属性注入
service 注入 dao,在 dao 注入 JdbcTemplate,在 JdbcTemplate 注入 DataSource
3、在dao创建两个方法:多钱和少钱的方法,在service创建转账方法

  1. //service
  2. @Service
  3. public class UserService {
  4. //注入 dao
  5. @Autowired
  6. private UserDao userDao;
  7. //转账的方法
  8. public void accountMoney() {
  9. //lucy 少 100
  10. userDao.reduceMoney();
  11. //mary 多 100
  12. userDao.addMoney();
  13. }
  14. }
  15. //dao
  16. @Repository
  17. public class UserDaoImpl implements UserDao {
  18. @Autowired
  19. private JdbcTemplate jdbcTemplate;
  20. //lucy 转账 100 给 mary
  21. //少钱
  22. @Override
  23. public void reduceMoney() {
  24. String sql = "update t_account set money=money-? where username=?";
  25. jdbcTemplate.update(sql,100,"lucy");
  26. }
  27. //多钱
  28. @Override
  29. public void addMoney() {
  30. String sql = "update t_account set money=money+? where username=?";
  31. jdbcTemplate.update(sql,100,"mary");
  32. }
  33. }

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

  1. <!-- 组件扫描 -->
  2. <context:component-scan base-package="com.atguigu"></context:component-scan>
  3. <!-- 数据库连接池 -->
  4. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
  5. destroy-method="close">
  6. <property name="url" value="jdbc:mysql:///user_db" />
  7. <property name="username" value="root" />
  8. <property name="password" value="root" />
  9. <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  10. </bean>
  11. <!-- JdbcTemplate对象 -->
  12. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  13. <!--注入dataSource-->
  14. <property name="dataSource" ref="dataSource"></property>
  15. </bean>

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

  • 开启事务
  • 进行业务操作
  • 如果没有发生异常提交事务
  • 出现异常的话进行回滚(在catch执行)

    3 事务操作

    1、事务添加到 JavaEE 三层结构里面 Service 层(业务逻辑层)
    2、在 Spring 进行事务管理操作有两种方式:编程式事务管理和声明式事务管理(使用)
    3、声明式事务管理
    (1)基于注解方式(使用)
    (2)基于 xml 配置文件方式
    4、在 Spring 进行声明式事务管理,底层使用 AOP 原理
    5、Spring 事务管理 API
    提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类
    image.png

    3.1 注解声明式事务管理

    1、配置文件配置事务管理器 ```java
  1. 2、开启事务注解<br />(1)在配置文件引入名称空间tx
  2. ```java
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xmlns:aop="http://www.springframework.org/schema/aop"
  7. xmlns:tx="http://www.springframework.org/schema/tx"
  8. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
  11. 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共有以下参数
image.png
(1)propagation()为传播行为,主要有以下7种
image.png
所谓的事务方法:对数据库表数据进行变化的操作
image.png
(2)isolation:事务隔离级别
多事务之间操作如果有隔离不会发生什么事情,但没有隔离会发生以下三种情况:脏读、不可重复读、虚(幻)读

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

image.png

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

image.png

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

为了防止以上情况,设置事务的隔离性
image.png
(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();
}