spice and wolfspice and wolf Be the One you wanna Be

Spring事务管理

事务并发问题(隔离性导致)

  • 脏读。一个事务读取到另一个事务未提交的数据。
  • 不可重复读。一个事务因读取到另一个事务已提交的数据(update),导致对同一条记录的多次读取结果不一致。
  • 幻读。一个事务因读取到另一个事务已提交的数据(insert、delete),导致对同一张表的多次读取结果不一致。

事务隔离级别

  • mysql的事务隔离级别。默认隔离级别为可重复读
    • Read uncommitted(读未提交):最低级别,任何情况都无法保证。
    • Read committed(读已提交):可避免脏读的发生。
    • Repeatable read(可重复读):可避免脏读、不可重复读的发生。
    • Serializable(串行化):可避免脏读、不可重复度、幻读的发生。
  • oracle的事务隔离级别。默认隔离级别为读已提交
    • Read committed(读已提交):可避免脏读的发生。
    • Serializable(串行化):可避免脏读、不可重复度、幻读的发生。
    • Read only(只读)

Spring事务管理接口

spring并不直接管理事务,而是提供了事务管理接口plantformTran

Spring事务管理分类

  • spring编程式事务管理(不推荐)。
  • spring申明式事务管理(底层采用AOP技术)。

xml方式事务管理

配置事务管理的AOP

  • 平台事务管理器。DataSourceTransactionManager
<!-- 配置平台事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 注入数据源 -->
    <property name="dataSource" ref="dataSource"></property>
</bean>
  • 事务通知
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!-- 配置事务相关属性 -->
    <tx:attributes>
        <tx:method name="transfer"/>
        <tx:method name="submitOrder"/>
    </tx:attributes>
</tx:advice>
  • AOP配置
<aop:config>
    <aop:advisor advice:ref="txAdvice" point-cut="execution(*cn..service.*.*(..))"/>
</aop:config>

混合方式事务管理

  • 类或方法上加注解。@Transactional
  • 开启事务注解
<!-- 配置平台事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 注入数据源 -->
    <property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transationManager"/>

基于AspectJ的纯注解方式

  • 配置类上加注解。@EnableTransactionManager

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Press ESC to close