Spring —— @Transacitonal 注解详解

引言: 

spring中@Transactional提供一种控制事务管理的快捷手段,但是很多人都只是@Transactional简单使用,并未深入了解,其各个配置项的使用方法,本文将深入讲解各个配置项的使用。

更多日志:

JDBC 事务详解:http://blog.csdn.net/qq_19865749/article/details/75369529

Hibernate 事务管理:http://blog.csdn.net/qq_19865749/article/details/75353874


一、 @Transactional的定义

Spring中的@Transactional基于动态代理的机制,提供了一种透明的事务管理机制,方便快捷解决在开发中碰到的问题。在现实中,实际的问题往往比我们预期的要复杂很多,这就要求对@Transactional有深入的了解,以来应对复杂问题。

首先我们来看看@Transactional的代码定义:

[html]  view plain  copy
  1. @Target({ElementType.METHOD, ElementType.TYPE})  
  2. @Retention(RetentionPolicy.RUNTIME)  
  3. @Inherited  
  4. @Documented  
  5. public @interface Transactional {  
  6.   
  7.     /**  
  8.      * A qualifier value for the specified transaction.  
  9.      * <p>May be used to determine the target transaction manager,  
  10.      * matching the qualifier value (or the bean name) of a specific  
  11.      * {@link org.springframework.transaction.PlatformTransactionManager}  
  12.      * bean definition.  
  13.      */  
  14.     String value() default "";  //有多个事务管理器时,用value指定使用哪个事务管理器
  15.   
  16.     /**  
  17.      * The transaction propagation type. Defaults to {@link Propagation#REQUIRED}.  
  18.      * @see org.springframework.transaction.interceptor.TransactionAttribute#getPropagation      * Behavior()  
  19.      */  
  20.     Propagation propagation() default Propagation.REQUIRED;  //传播方式。常用
  21.   
  22.     /**  
  23.      * The transaction isolation level. Defaults to {@link Isolation#DEFAULT}.  
  24.      * @see org.springframework.transaction.interceptor.TransactionAttribute#getIsolationLe      * -vel()  
  25.      */  
  26.     Isolation isolation() default Isolation.DEFAULT;  //事务隔离水平(了解事务隔离)
  27.   
  28.     /**  
  29.      * The timeout for this transaction.  
  30.      * Defaults to the default timeout of the underlying transaction system.  
  31.      * @see org.springframework.transaction.interceptor.TransactionAttribute#getTimeout()  
  32.      */  
  33.     int timeout() default TransactionDefinition.TIMEOUT_DEFAULT;  
  34.   
  35.     /**  
  36.      * {@code true} if the transaction is read-only.  
  37.      * Defaults to {@code false}.  
  38.      * <p>This just serves as a hint for the actual transaction subsystem;  
  39.      * it will <i>not necessarily</i> cause failure of write access attempts.  
  40.      * A transaction manager which cannot interpret the read-only hint will  
  41.      * <i>not</i> throw an exception when asked for a read-only transaction.  
  42.      * @see org.springframework.transaction.interceptor.TransactionAttribute#isReadOnly()  
  43.      */  
  44.     boolean readOnly() default false;  
  45.   
  46.     /**  
  47.      * Defines zero (0) or more exception {@link Class classes}, which must be a  
  48.      * subclass of {@link Throwable}, indicating which exception types must cause  
  49.      * a transaction rollback.  
  50.      * <p>This is the preferred way to construct a rollback rule, matching the  
  51.      * exception class and subclasses.  
  52.      * <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(Class clazz)}  
  53.      */  
  54.     Class<? extends Throwable>[] rollbackFor() default {};  
  55.   
  56.     /**  
  57.      * Defines zero (0) or more exception names (for exceptions which must be a  
  58.      * subclass of {@link Throwable}), indicating which exception types must cause  
  59.      * a transaction rollback.  
  60.      * <p>This can be a substring, with no wildcard support at present.  
  61.      * A value of "ServletException" would match  
  62.      * {@link javax.servlet.ServletException} and subclasses, for example.  
  63.      * <p><b>NB: </b>Consider carefully how specific the pattern is, and whether  
  64.      * to include package information (which isn't mandatory). For example,  
  65.      * "Exception" will match nearly anything, and will probably hide other rules.  
  66.      * "java.lang.Exception" would be correct if "Exception" was meant to define  
  67.      * a rule for all checked exceptions. With more unusual {@link Exception}  
  68.      * names such as "BaseBusinessException" there is no need to use a FQN.  
  69.      * <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(String exceptionName)}  
  70.      */  
  71.     String[] rollbackForClassName() default {};  
  72.   
  73.     /**  
  74.      * Defines zero (0) or more exception {@link Class Classes}, which must be a  
  75.      * subclass of {@link Throwable}, indicating which exception types must <b>not</b>  
  76.      * cause a transaction rollback.  
  77.      * <p>This is the preferred way to construct a rollback rule, matching the  
  78.      * exception class and subclasses.  
  79.      * <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(Class clazz)}  
  80.      */  
  81.     Class<? extends Throwable>[] noRollbackFor() default {};  
  82.   
  83.     /**  
  84.      * Defines zero (0) or more exception names (for exceptions which must be a  
  85.      * subclass of {@link Throwable}) indicating which exception types must <b>not</b>  
  86.      * cause a transaction rollback.  
  87.      * <p>See the description of {@link #rollbackForClassName()} for more info on how  
  88.      * the specified names are treated.  
  89.      * <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(String exceptionName)}  
  90.      */  
  91.     String[] noRollbackForClassName() default {};  
  92.   
  93. }  
基于源代码,我们可以发现在@Transactional,原来有这么多的属性可以进行配置,从而达到复杂应用控制的目的。具体各个属性的用法和作用,将在本文的后面逐一进行讲解和说明。


二、 使用@Transactional的Spring配置

为了使用基于@Transactional的事务管理,需要在spring-context.xml 中进行如下配置:

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
	<property name="entityManagerFactory" ref="emf" />
</bean>
<!-- tx:annotation-driven 启用@Transactional 注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
其中引用的 emf 可以为LocalContainerEntityManagerFactory bean:

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
	<property name="dataSource" ref="dataSource" />  
</bean>
dataSource 指定了该实体管理器工厂bean 所使用的数据源,当采用c3p0 连接池时,查看另一篇日志:

spring 使用 c3p0 连接池:http://blog.csdn.net/qq_19865749/article/details/75376657

同时该LocalContainerEntityManagerFactoryBean 会自动扫描类路径下的persistence.xml 文件,该文件中定义了持久化单元,即定义了dataSource中所指定的数据库中的表与程序中实体的对应关系(基于JPA 提供者)。使用Hibernate 中的JPA 时定义细节查看另一篇日志:

Hibernate 持久化:

本质上,@Transactional使用了JDBC的事务来进行事务控制的。


三、@Transactional 各值作用

1、 @Transactional之value

value这里主要用来指定不同的事务管理器;主要用来满足在同一个系统中,存在不同的事务管理器。比如在Spring中,声明了两种事务管理器txManager1, txManager2.

然后,用户可以根据这个参数来根据需要指定特定的txManager.

那问题是情况下会存在多个事务管理器的情况呢? 当在一个系统中,需要访问多个数据源或者多个数据库,则必然会配置多个事务管理器的。

2、@Transactional之propagation

Propagation支持7种不同的传播机制:

REQUIRED

        业务方法需要在一个事务中运行,如果方法运行时,已处在一个事务中,那么就加入该事务,否则自己创建一个新的事务.这是spring默认的传播行为.。 

SUPPORTS 

        如果业务方法在某个事务范围内被调用,则方法成为该事务的一部分,如果业务方法在事务范围外被调用,则方法在没有事务的环境下执行。 MANDATORY

        只能在一个已存在事务中执行,业务方法不能发起自己的事务,如果业务方法在没有事务的环境下调用,就抛异常

REQUIRES_NEW

        业务方法总是会为自己发起一个新的事务,如果方法已运行在一个事务中,则原有事务被挂起,新的事务被创建,直到方法结束,新事务才结束,原先的事务才会恢复执行.

NOT_SUPPORTED

        声明方法需要事务,如果方法没有关联到一个事务,容器不会为它开启事务.如果方法在一个事务中被调用,该事务会被挂起,在方法调用结束后,原先的事务便会恢复执行.

NEVER

        声明方法绝对不能在事务范围内执行,如果方法在某个事务范围内执行,容器就抛异常.只有没关联到事务,才正常执行.

NESTED

        如果一个活动的事务存在,则运行在一个嵌套的事务中.如果没有活动的事务,则按REQUIRED属性执行.它使用了一个单独的事务, 这个事务拥有多个可以回滚的保证点.内部事务回滚不会对外部事务造成影响, 它只对DataSourceTransactionManager 事务管理器起效.


其实大家最感到困惑的是REQUIRED_NEW和NESTED两种不同的传播机制,功能类似,都涉及到了事务嵌套的问题,那两者有何区别呢?该如何正确使用这两种模式呢?

以下是摘自Spring的文档:
	PROPAGATION_REQUIRES_NEW : uses a completely independent transaction for each affected transaction scope. In that case, the underlying physical transactions are different and hence can commit or roll back independently, with an outer transaction not affected by an inner transaction's rollback status.
        内部的事务独立运行,在各自的作用域中,可以独立的回滚或者提交;而外部的事务将不受内部事务的回滚状态影响。 
        ROPAGATION_NESTED : uses a single physical transaction with multiple savepoints that it can roll back to. Such partial rollbacks allow an inner transaction scope to trigger a rollback for its scope, with the outer transaction being able to continue the physical transaction despite some operations having been rolled back. This setting is typically mapped onto JDBC savepoints, so will only work with JDBC resource transactions.
       NESTED的事务,基于单一的事务来管理,提供了多个保存点。这种多个保存点的机制允许内部事务的变更触发外部事务的回滚。而外部事务在混滚之后,仍能继续进行事务处理,即使部分操作已经被混滚。 由于这个设置基于JDBC的保存点,所以只能工作在JDBC的机制智商。

由此可知, 两者都是事务嵌套,不同之处在于,内外事务之间是否存在彼此之间的影响;NESTED之间会受到影响,而产生部分回滚,而REQUIRED_NEW则是独立的。


参考日志:http://blog.csdn.net/blueheart20/article/details/44654007/



  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
@Autowired注解用于自动装配Spring容器中的Bean。当标注在构造函数上时,会将符合类型的Bean自动注入到构造函数中作为参数。如果属性是一个接口类型,它会根据类型找到对应的实现类进行注入。如果有多个实现类,可以结合@Qualifier注解指定具体要注入的实现类的名称。 需要注意的是,在BeanPostProcessor类和BeanFactoryPostProcessor类中无法使用@Autowired注解。因为@Autowired注解的收集工作是由BeanPostProcessor类完成的,而BeanFactoryPostProcessor类的调用时机先于BeanPostProcessor类,所以无法使用@Autowired注解在这两个类中。 另外,如果想禁用某些特定构造函数的自动装配,可以使用注释将其注释掉。比如在代码中使用/* */将构造函数注释掉,可以阻止@Autowired注解的自动注入。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [@Autowired注解详解——超详细易懂](https://blog.csdn.net/weixin_45755816/article/details/118654961)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [@Autowired注解详解](https://blog.csdn.net/qq1309664161/article/details/119293360)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值