因为在不同平台,操作的事务的代码各不相同Spring提供了一个接口
PlatformTransationManager接口
在事务中最核心的接口PlatformTransationManager
对不同的框架有不同的实现类:
org.springframework.jdbc.datasource.DataSourceTransactionManager 使用 Spring
JDBC 或 iBatis 进行持久化数据时使用
org.springframework.orm.hibernate3.HibernateTransactionManager 使用
Hibernate 版本进行持久化数据时使用
TransactionDefinition:事务定义信息
事务定义信息:
隔离级别
传播行为
超时信息
是否只读
TransactionStatus:事务的状态
记录事务的状态
事务的传播行为(基本都使用PROPAGATION_REQUIRED)
PROPAGION_XXX :事务的传播行为
保证同一个事务中
PROPAGATION_REQUIRED 支持当前事务,如果不存在 就新建一个(默认)
PROPAGATION_SUPPORTS 支持当前事务,如果不存在,就不使用事务
PROPAGATION_MANDATORY 支持当前事务,如果不存在,抛出异常
保证没有在同一个事务中
PROPAGATION_REQUIRES_NEW 如果有事务存在,挂起当前事务,创建一个新的事务
PROPAGATION_NOT_SUPPORTED 以非事务方式运行,如果有事务存在,挂起当前事务
代码
1导包
2导入约束
3代码
<!-- 配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="persist*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="update*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="modify*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="delete*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="remove*" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
<tx:method name="get*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
<tx:method name="find*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/>
<tx:method name="transfer" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
</tx:attributes>
</tx:advice>
<!-- 配置织入 -->
<aop:config>
<!--记住(* com.itheima.service.*ServiceImpl.*(..)这里*开头后有个空格 -->
<aop:pointcut expression="execution(* com.itheima.service.*ServiceImpl.*(..))" id="txPc"/>
<!-- 配置切面 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/>
</aop:config>
注解配置事务
核心配置文件中开启注解配置事务
<tx:annotation-driven/>
在需要配置的类上或者方法上写入注释
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false)