尚硅谷-Spring5.2.6-源码讲解课程-事务篇

事务?大学学过数据库的童鞋应该对事务有了解,最最经典的例子就是银行转账问题。所以,如果没有事务管理,可能出现哪些问题就不用我多废话了!

事务的四大特性

ACID,很重要!面试会问的。原子性、一致性、隔离性、持久性。

针对这四个特性,最好加一下自己的理解。比如:

1.事务是逻辑上的一组操作,要么全执行,要么全不执行,这也意味着一组操作不可分割,即原子性;2.一致性是说一个事务前后,数据库的逻辑含义是一致的,比如银行转账过程中,钱的总数是不变的;3.多个用户操作数据库,执行各自的事务时,是相互隔离的,这就是隔离性;4.最后就是,所有数据库的操作,事务提交之后,数据就会写进数据库的文件中,进行落盘,下次查看或操作数据库是基于上次事务之后进行的,这就是持久性。

事务的底层原理

底层就是之前学过的AOP技术,面向切面编程,也很好理解,就是在业务逻辑前后切入方法,正常执行就提交事务,异常就回滚事务。

面试过程中如果问到事务的底层原理,答上来之后,就可以直接说AOP的底层原理了。

事务管理的实现方式

两种!编程式事务管理,说白了,就是开发人员自己手写try-catch代码;还有就是声明式事务管理,实际开发中使用的就是Spring提供的声明式事务管理,声明式事务管理参考之前Spring提供的各种框架,也分为xml配置和注解方式实现,实际工作中也就是使用注解方式。

声明式事务管理

注解方式实现

以银行转账为例

@Service
public class AccountService {

    @Autowired
    private AccountDao accountDao;

    //模拟1001用户给1002用户转账500
    public void transfer() {
        accountDao.decrease(500, "1001");

        accountDao.increase(500, "1002");
    }
}
public interface AccountDao {
    public void increase(int money, String id);
    public void decrease(int money, String id);
}
@Repository
public class AccountDaoImpl implements AccountDao{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void increase(int money, String id) {
        String sql = "update account set account = account + ? where id = ?";
        jdbcTemplate.update(sql, money, id);
    }

    @Override
    public void decrease(int money, String id) {
        String sql = "update account set account = account - ? where id = ?";
        jdbcTemplate.update(sql, money, id);
    }
}

 测试类

@Test
public void test01() {
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("jdbcbean.xml");
    AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
    accountService.transfer();
}

 

配置事务管理

创建事务管理器TransactionManager

引入tx名称空间,开启事务注解

<?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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

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

    <!--配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:13306/dbtest"/>
        <property name="username" value="root"/>
        <property name="password" value="qts0922"/>
    </bean>

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

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

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

添加@Transactional注解

建议在业务类上添加注解,而不是持久层或其他架构中添加事务注解;

在类上添加注解,则类中的所有方法都会开启事务管理;若只是在某个或某些方法上添加注解,则仅仅是该方法会开启事务。 

@Service
@Transactional
public class AccountService {

    @Autowired
    private AccountDao accountDao;

    //模拟1001用户给1002用户转账500
    public void transfer() {
        accountDao.decrease(500, "1001");
        int i = 1/0;
        accountDao.increase(500, "1002");
    }
}

@Transactional注解的属性

传播行为propagation

事务传播行为,当一个事务被另一个事务调用,这个事务应该如何处理的问题。

 

 

REQUIRED:如果有事务在运行,当前的方法就在这个事务内运行,否则,就启动一个新的事务,并在自己的事务内运行。简单理解就是,有事务就加入,没事务就自己整个事务。

REQUIRED_NEW:当前的方法必须启动新事务,并在它自己的事务内运行,如果有事务正在运行,应该将它挂起。简单理解就是,不管是不是一个已有事务的方法调用我,我都要创建一个属于我自己的事务。

SUPPORTS:如果有事务在运行,当前的方法就在这个事务内运行,否则它可以不运行在事务中。简单理解就是,有事务就加入,没事务就拉倒,就别整事务了,就是普通方法了。

NOT_SUPPORTED:当前的方法不应该运行在事务中,如果有运行的事务,将它挂起。简单理解就是,有事务不行,事务管理器不能管我,我自己运行自己的,执行完了事务管理器继续。

MANDATORY:当前的方法必须运行在事务内部,如果没有正在运行的事务,就抛出异常。

NEVER:当前的方法不应该运行在事务中,如果有运行的事务,就抛出异常。

NESTED:如果有事务在运行,当前的方法就应该在这个事务的嵌套事务内运行,否则,就启动一个新的事务,并在它自己的事务上运行。简单理解,跟REQUIRED差不多,只是有事务的时候是嵌套事务,不是直接加入。

隔离级别isolation

事务有4种隔离级别,对应解决不同的事务操作问题。

1.脏读:一个未提交事务读取到另一个未提交事务的数据。

2.不可重复读:一个未提交事务读取到另一个已提交事务修改后的数据。从1变成2

3.幻读:一个未提交事务读取到另一个已提交事务添加的数据。从无到有

隔离级别:

读未提交,上述3种问题都有

读已提交,解决了脏读的问题,oracle默认的隔离级别

可重复读,解决了脏读和不可重复读的问题,mysql默认的隔离级别

串行化,三种问题都解决了,但数据库的性能严重下降

超时时间timeout

要求事务在一定时间内提交,否则就会回滚。默认值-1,即一直会等待。单位:秒

是否只读readOnly

读:查询操作;写:增删改;默认是false

回滚rollbackFor

设置出现哪些异常会回滚:Throwable的子类集合

Class<? extends Throwable>[] rollbackFor() default {};

不回滚noRollbackFor

设置出现哪些异常不会回滚:Throwable的子类集合

Class<? extends Throwable>[] noRollbackFor() default {};
@Transactional(propagation = Propagation.REQUIRED,
        isolation = Isolation.REPEATABLE_READ,
        timeout = 30,
        readOnly = false,
        rollbackFor = {TimeoutException.class},
        noRollbackFor = {RefreshFailedException.class}
)

XML配置文件方式实现

底层原理:AOP面向切面编程

<?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"
       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">

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

    <!--配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:13306/dbtest"/>
        <property name="username" value="root"/>
        <property name="password" value="qts0922"/>
    </bean>

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

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

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

    <!--配置通知-->
    <tx:advice id="txAdvice">
        <!--配置事务参数-->
        <tx:attributes>
            <!--指明哪些方法或规则上需要开启事务,方法名可以模糊匹配,并附上事务属性-->
            <tx:method name="transfer" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!--配置切入点和切面-->
    <aop:config>
        <!--配置切入点表达式,在com.coffeeship.service.AccountService类下的所有方法都作为切入点-->
        <aop:pointcut id="pointCut" expression="execution(* com.coffeeship.service.AccountService.*(..))"/>
        <!--配置切面:将事务通知切入到切入点-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>
    </aop:config>
</beans>

 完全注解开发

@Configuration
@ComponentScan(basePackages = "com.coffeeship")
@EnableTransactionManagement //开启事务
public class TxConfig {

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

    //创建JdbcTemplate对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值