您的位置:首页 > 编程语言 > Java开发

Spring review--事务的传播特性

2016-08-11 17:57 274 查看
  Spring的事务有两种管理方式:编程式事务管理,声明式事务管理。编程式就是在java代码中实现的事务,跟jdbc的事务类似。声明式事务在xml中配置出来的,迎合了Spring侵入性小的特点。

  事务的传播特性,常用的是第一个:

PROPAGATION_REQUIRED
如果存在一个事物,则支持当前事务。如果没有事务则开启。
PROPAGATION_SUPPORTS
如果存在一个事务,支持当前事务。如果没有事务,则非事务的执行
PROPAGATION_MANDATORY
如果已经存在一个事务,则支持当前事务。如果没有一个活动的事务,则抛出异常
PROPAGATION_REQUIRES_NEW
总是开启一个新的事务,如果一个事务已经存在,则将这个存在的事务
挂起。
PROPAGATION_Not_SUPPORTED
总是非事务的执行,并挂起任何存在的事务。
PROPAGATION_NEVER
总是非事务的执行,如果存在一个活动事务,则抛出异常
 
PROPAGATION_NESTED
如果一个活动的事务存在,则运行在一个嵌套的事务中,如果没有活动事务,则按required属性执行。
下面是声明式事务管理的配置文件内容:

<span style="font-family:Microsoft YaHei;font-size:14px;"><span style="font-family:Microsoft YaHei;font-size:14px;"><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd" default-autowire="byName">
<!-- 配置SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>

<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"></ref>
</property>
</bean>

<aop:config>
<aop:pointcut id="allManagerMethod" expression="execution (* com.bjpowernode.usermgr.manager.*.*)"/>
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>
</aop:config>

<!-- 事务的传播特性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
</tx:advice>
</beans>
</span></span>


  编程式事务跟声明式事务试用场景不同,有很少的事务操作时,编程式事务比较合适,针对性比较强;如果应用中存在大量事务操作,那么声明式事务管理通常是值得的,它将事务管理与业务逻辑隔离,配置成本极大降低。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: