事务操作的四个特性:重点掌握
原子性
一致性
隔离性
永久性
问题引入:
事务操作过程:
编程式事务管理:
声明式事务管理(使用)
基于注解方式:
1、在 Spring 进行声明式事务管理,底层使用 AOP 原理
2、Spring 事务管理 API
实现步骤:
<!--1、在 spring 配置文件配置事务管理器-->
<!--创建事务管理器-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--2、在 spring 配置文件,开启事务注解-->
<!--(1)在 spring 配置文件引入名称空间 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 transactionmanager="transactionManager"></tx:annotation-driven>
<!--3、在 service 类上面(或者 service 类里面方法上面)添加事务注解-->
<!--(1)@Transactional,这个注解添加到类上面,也可以添加方法上面-->
<!--(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务-->
<!--(3)如果把这个注解添加方法上面,为这个方法添加事务-->
基于xml进行事务管理(可以帮助了解事务功能实现的原理)
<!--1 创建事务管理器-->
<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>