Spring的事务

  首先我们的知道事实上Spring并不直接管理事务,而是提供了多种事务管理器。他们将事务管理的职责委托给Hibernate或者JTA等持久化机制所提供的相关平台框架的事务来实现。

  Spring的事务主要分为:编程式事务、声明式事务

  第一步的必须配置事务管理器(其中的dataSource是事务源)

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

  对于编程式事务我们采用的配置:

1:编程式事务管理
<!--配置事务管理的模板-->
 <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
   <property name="transactionManager" ref="transactionManager"></property>
   <!--定义事务隔离级别,-1表示使用数据库默认级别-->
  <property name="isolationLevelName" value="ISOLATION_DEFAULT"></property>
  <property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"></property>   
</bean>

  对于声明式事务我的常用配置如下:

  首先和大家分享一下总结的声明式事务有如下方式

    1、使用bean代理(一个bean一个代理)

    2、使用bean代理(多个bean一个代理)

      3、使用拦截器

    4、使用tx标签

    5、使用全注解

  我常用的配置就是4、5

    4、对于tx的配置(个人常用) 

2:声明式事务管理 :一种是tx的,一种是一种是基于@Transactional注解
<aop:config>
  <aop:pointcut id="pointCut" expression="execution (* com.gray.service.*.*(..))"/>
  <aop:advisor advice-ref="advice" pointcut-ref="pointCut"/>
</aop:config>
<tx:advice id="advice" transaction-manager="transactionManager">
   <tx:attributes>
    <tx:method name="insert" propagation="REQUIRED" read-only="false" rollback-for="Exception"/>
   </tx:attributes>
</tx:advice>

    5、全注解(个人常用)

<tx:annotation-driven transaction-manager="transactionManager"/>

  

原文地址:https://www.cnblogs.com/karrya/p/11599828.html