spring中的事务实现

什么事务

( 1)事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操
作都失败
(2)典型场景:银行转账

  • lucy 转账 100 元 给 mary
  • lucy 少 100, mary 多 100

事务四个特性(ACID)

(1)原子性
(2)一致性
(3)隔离性
(4)持久性

环境准备

搭建环境,先确保可以执行
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--引入数据库配置信息 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--创建JdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--开启注解扫描-->
    <context:component-scan base-package="com.transaction"/>

</beans>

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

public interface UserDao {
    //多钱
    void addMoney();
    //少钱
    void reduceMoney();
}
@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");
    }
}
@Service
public class UserService {
    //注入dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney() {
        userDao.reduceMoney();
        userDao.addMoney();
    }
}
 	@Test
    public void testTx() {
        ApplicationContext context = new ClassPathXmlApplicationContext("TestBean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountMoney();
    }

在这里插入图片描述

在没有错误的情况下,转账功能正确。

人为制造异常
	//转账的方法
    public void accountMoney() {
        userDao.reduceMoney();
        int result=10/0;
        userDao.addMoney();
    }

这时出现问题,lucy钱少了,但mary钱没有增加。

Spring 事务管理介绍

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

编程式事务问题操作过程

    //转账的方法
    public void accountMoney() {
        try {
            //第一步 开启事务
            //第二步 进行业务操作
            //lucy少100
            userDao.reduceMoney();
            //模拟异常
            int i = 10/0;
            //mary多100
            userDao.addMoney();
            //第三步 没有发生异常,提交事务
       }catch(Exception e) {
            //第四步 出现异常,事务回滚
       }
    }

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

在spring配置文件中进行配置

    <!--创建事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源,ref引用自定义的数据原-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

基于注解方式:在类或方法上面加事务注解@Transactional

  • 如果@Transactional添加在类上面,这个类里面的所有方法都添加事务
  • 如果@Transactional添加方法上面,只是为该方法都添加事务
@Service
@Transactional
public class UserService {
    //注入dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney() {
        userDao.reduceMoney();
        int result=10/0;
        userDao.addMoney();
    }
}

现在程序抛出异常,事务回滚,两个人的金额不变,

@Transactional注解中的参数说明

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Transactional {
    @AliasFor("transactionManager")
    String value() default "";
    @AliasFor("value")
    String transactionManager() default "";
    Propagation propagation() default Propagation.REQUIRED;
    Isolation isolation() default Isolation.DEFAULT;
    int timeout() default -1;
    boolean readOnly() default false;
    Class<? extends Throwable>[] rollbackFor() default {};
    String[] rollbackForClassName() default {};
    Class<? extends Throwable>[] noRollbackFor() default {};
    String[] noRollbackForClassName() default {};
}

部分参数介绍

propagation 事务的传播行为

多事务方法直接进行调用,这个过程中的事务是如何进行管理的?

在这里插入图片描述

在这里插入图片描述
默认:propagation = Propagation.REQUIRED

isolation 事务的隔离级别

(1)事务有特性称为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题
(2)有三个读问题:脏读、不可重复读、虚(幻)读
(3)脏读:一个未提交事务读取到另一个未提交事务的数据
在这里插入图片描述

(4)不可重复读:一个未提交事务读取到另一提交事务修改数据

在这里插入图片描述

(5)幻读:一个未提交事务读取到另一提交事务添加数据

(6) 解决: 通过设置事务隔离级别,解决读问题
在这里插入图片描述
默认:isolation = Isolation.REPEATABLE_READ

timeout 超时时间

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

readOnly 是否只读

(1)读:查询操作,写:添加修改删除操作
(2) readOnly 默认值 false,表示可以查询,可以添加修改删除操作
(3)设置 readOnly 值是 true,设置成 true 之后,只能查询

rollbackFor 回滚

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

noRollbackFor 不回滚

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值