编程式事务控制相关对象
三大控制对象:
平台事务管理器
事务定义
事务状态
平台事务管理器需要自己指定,事务定义也得指定各种参数(隔离级别、传播行为、超时时间、是否只读)
数据库事务的四大隔离级别:读未提交、读已提交、可重复读、串行化
基于xml的声明式事务控制
在applicationContext.xml中进行事务的配置:
- 配置切点(要增强的方法所在的类)
- 配置平台事务管理器
使用的是jdbc的DataSourceTransactionManager
需要注入dataSource - 配置通知(切面)——事务的增强
这里事务定义的切面不是aspect而是tx:advice标签 - 配置事务的织入
<!--目标对象 内部的方法就是切点-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!--配置平台事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--通知 事务的增强-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--设置事务的属性信息的-->
<tx:attributes>
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="save" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false"/>
<tx:method name="findAll" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
<tx:method name="update*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!--配置事务的aop织入-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.itheima.service.impl.*.*(..))"/>
<!--aop:advisor专门指的是事务的增强,aop:aspect是一般的切面定义-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
基于注解的声明式事务控制
需要在xml文件中配置一下事务管理器,然后再配置事务的注解驱动,注意一定要开组件扫描,扫描注入的注解组件
<!--组件扫描-->
<context:component-scan base-package="com.itheima"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--事务的注解驱动-->
<tx:annotation-driven transaction-manager="transactionManager"/>
然后方法或者类上面加上一个事务注解@Transactional即可