Spring中@Transactional用法详细介绍

 更新时间:2017年02月10日 10:44:45   作者:bladestone  
这篇文章主要介绍了Spring中@Transactional用法详细介绍的相关资料,需要的朋友可以参考下

Spring中@Transactional用法详细介绍

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

1.  @Transactional的定义

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

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

@Target({ElementType.METHOD, ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
@Inherited 
@Documented 
public @interface Transactional { 
 
  /** 
   * A qualifier value for the specified transaction. 
   * <p>May be used to determine the target transaction manager, 
   * matching the qualifier value (or the bean name) of a specific 
   * {@link org.springframework.transaction.PlatformTransactionManager} 
   * bean definition. 
   */ 
  String value() default ""; 
 
  /** 
   * The transaction propagation type. 
   * Defaults to {@link Propagation#REQUIRED}. 
   * @see org.springframework.transaction.interceptor.TransactionAttribute#getPropagationBehavior() 
   */ 
  Propagation propagation() default Propagation.REQUIRED; 
 
  /** 
   * The transaction isolation level. 
   * Defaults to {@link Isolation#DEFAULT}. 
   * @see org.springframework.transaction.interceptor.TransactionAttribute#getIsolationLevel() 
   */ 
  Isolation isolation() default Isolation.DEFAULT; 
 
  /** 
   * The timeout for this transaction. 
   * Defaults to the default timeout of the underlying transaction system. 
   * @see org.springframework.transaction.interceptor.TransactionAttribute#getTimeout() 
   */ 
  int timeout() default TransactionDefinition.TIMEOUT_DEFAULT; 
 
  /** 
   * {@code true} if the transaction is read-only. 
   * Defaults to {@code false}. 
   * <p>This just serves as a hint for the actual transaction subsystem; 
   * it will <i>not necessarily</i> cause failure of write access attempts. 
   * A transaction manager which cannot interpret the read-only hint will 
   * <i>not</i> throw an exception when asked for a read-only transaction. 
   * @see org.springframework.transaction.interceptor.TransactionAttribute#isReadOnly() 
   */ 
  boolean readOnly() default false; 
 
  /** 
   * Defines zero (0) or more exception {@link Class classes}, which must be a 
   * subclass of {@link Throwable}, indicating which exception types must cause 
   * a transaction rollback. 
   * <p>This is the preferred way to construct a rollback rule, matching the 
   * exception class and subclasses. 
   * <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(Class clazz)} 
   */ 
  Class<? extends Throwable>[] rollbackFor() default {}; 
 
  /** 
   * Defines zero (0) or more exception names (for exceptions which must be a 
   * subclass of {@link Throwable}), indicating which exception types must cause 
   * a transaction rollback. 
   * <p>This can be a substring, with no wildcard support at present. 
   * A value of "ServletException" would match 
   * {@link javax.servlet.ServletException} and subclasses, for example. 
   * <p><b>NB: </b>Consider carefully how specific the pattern is, and whether 
   * to include package information (which isn't mandatory). For example, 
   * "Exception" will match nearly anything, and will probably hide other rules. 
   * "java.lang.Exception" would be correct if "Exception" was meant to define 
   * a rule for all checked exceptions. With more unusual {@link Exception} 
   * names such as "BaseBusinessException" there is no need to use a FQN. 
   * <p>Similar to {@link org.springframework.transaction.interceptor.RollbackRuleAttribute#RollbackRuleAttribute(String exceptionName)} 
   */ 
  String[] rollbackForClassName() default {}; 
 
  /** 
   * Defines zero (0) or more exception {@link Class Classes}, which must be a 
   * subclass of {@link Throwable}, indicating which exception types must <b>not</b> 
   * cause a transaction rollback. 
   * <p>This is the preferred way to construct a rollback rule, matching the 
   * exception class and subclasses. 
   * <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(Class clazz)} 
   */ 
  Class<? extends Throwable>[] noRollbackFor() default {}; 
 
  /** 
   * Defines zero (0) or more exception names (for exceptions which must be a 
   * subclass of {@link Throwable}) indicating which exception types must <b>not</b> 
   * cause a transaction rollback. 
   * <p>See the description of {@link #rollbackForClassName()} for more info on how 
   * the specified names are treated. 
   * <p>Similar to {@link org.springframework.transaction.interceptor.NoRollbackRuleAttribute#NoRollbackRuleAttribute(String exceptionName)} 
   */ 
  String[] noRollbackForClassName() default {}; 
 
} 

  基于源代码,我们可以发现在@Transactional,原来有这么多的属性可以进行配置,从而达到复杂应用控制的目的。具体各个属性的用法和作用,将在本文的后面逐一进行讲解和说明。

2.  使用@Transactional的Spring配置

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

 <beans:bean id="transactionManager" 
  class="org.springframework.orm.jpa.JpaTransactionManager"> 
  <beans:property name="dataSource" ref="dataSource" /> 
  <beans:property name="entityManagerFactory" ref="entityManagerFactory" /> 
</beans:bean> 
 
<!-- 声明使用注解式事务 --> 
<tx:annotation-driven transaction-manager="transactionManager" /> 

      dataSource是在Spring配置文件中定义的数据源的对象实例,EntityManagerFactory是基于JPA使用的实体类管理器:org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean。这些都是用来配置与数据库的连接信息,本质上,@Transactional使用了JDBC的事务来进行事务控制的。

    <annotation-driven>标签的声明,则是在Spring内部启用@Transactional来进行事务管理,类似开关之类的声明。

3.  @Transactional之value

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

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

   那有同学会问什么情况下会存在多个事务管理器的情况呢? 比如在一个系统中,需要访问多个数据源或者多个数据库,则必然会配置多个事务管理器的。

4.   @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则是独立的。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

  • spring声明式事务@Transactional底层工作原理

    spring声明式事务@Transactional底层工作原理

    这篇文章主要为大家介绍分析spring声明式事务@Transactional底层工作原理,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步早日升职加薪
    2022-02-02
  • SpringBoot处理接口幂等性的两种方法详解

    SpringBoot处理接口幂等性的两种方法详解

    接口幂等性处理算是一个非常常见的需求了,我们在很多项目中其实都会遇到。本文为大家总结了两个处理接口幂等性的两种常见方案,需要的可以参考一下
    2022-06-06
  • 为什么说要慎用SpringBoot @ComponentScan

    为什么说要慎用SpringBoot @ComponentScan

    本文主要介绍了为什么说要慎用SpringBoot @ComponentScan,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧
    2021-07-07
  • Java中多媒体文件上传及页面回显的操作代码

    Java中多媒体文件上传及页面回显的操作代码

    这篇文章主要介绍了Java中多媒体文件上传及页面回显的操作代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • java Future 接口使用方法详解

    java Future 接口使用方法详解

    这篇文章主要介绍了java Future 接口使用方法详解,Future接口是Java线程Future模式的实现,可以来进行异步计算的相关资料,需要的朋友可以参考下
    2017-03-03
  • Java实现动态IP代理的步骤详解

    Java实现动态IP代理的步骤详解

    在网络编程中,动态IP代理可以帮助用户隐藏真实IP以及提高数据抓取的效率,本文将介绍如何在Java中实现动态IP代理,包括设置代理、发送请求以及处理响应,需要的朋友可以参考下
    2025-02-02
  • 手写redis@Cacheable注解 支持过期时间设置方式

    手写redis@Cacheable注解 支持过期时间设置方式

    这篇文章主要介绍了手写redis@Cacheable注解 支持过期时间设置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • 使用MultipartFile实现文件上传功能

    使用MultipartFile实现文件上传功能

    这篇文章主要介绍了使用MultipartFile实现文件上传功能,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-06-06
  • Java将Word文档转换为PDF文件的几种常用方法总结

    Java将Word文档转换为PDF文件的几种常用方法总结

    这篇文章主要介绍了Java将Word文档转换为PDF文件的四种常用方法,分别使用ApachePOI+iText、Aspose.Words for Java、Docx4j和JODConverter,这些库各有优点,但在使用时需要注意库与Java环境的兼容性、安装所需依赖、转换速度和资源消耗,需要的朋友可以参考下
    2024-10-10
  • 解决javac不是内部或外部命令,也不是可运行程序的报错问题

    解决javac不是内部或外部命令,也不是可运行程序的报错问题

    在学着使用Java的命令行来编译java文件的时候,遇到了这个问题,本文主要介绍了解决javac不是内部或外部命令,也不是可运行程序的报错问题,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04

最新评论