>  기사  >  Java  >  Spring의 @Transactional 사용법에 대한 자세한 소개

Spring의 @Transactional 사용법에 대한 자세한 소개

黄舟
黄舟원래의
2017-03-07 10:31:202161검색

이 글에서는 Spring의 @Transactional 사용법에 대한 관련 정보를 주로 소개하고 있으니, 필요하신 분들은

Spring의 @Transactional 사용법 상세 소개

소개: @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&#39;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 {}; 
 
}

소스 코드를 기반으로 @에서 찾을 수 있습니다. 트랜잭션의 경우 복잡한 애플리케이션 제어를 달성하기 위해 여러 속성을 구성할 수 있는 것으로 나타났습니다. 각 속성의 구체적인 사용법과 기능은 이 문서의 뒷부분에서 하나씩 설명하고 설명합니다.


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 트랜잭션을 사용합니다.


2c9e182d80bb0e092d1da29bee424e33 태그를 선언하면 스위치와 같은 문과 유사하게 Spring 내에서 @Transactional을 트랜잭션 관리할 수 있습니다.

3. @Transactional value

여기서 값은 주로 동일한 시스템 관리자에서 다양한 트랜잭션의 요구 사항을 충족하는 데 사용됩니다. 예를 들어 Spring에서는 txManager1과 txManager2라는 두 개의 트랜잭션 관리자가 선언됩니다.

그런 다음 사용자는 이 매개변수를 사용하여 필요에 따라 특정 txManager를 지정할 수 있습니다.

어떤 학생들은 무엇을 요구할지 모릅니다. 상황은 여러 트랜잭션 관리자가 있는 경우 어떻게 될까요? 예를 들어, 여러 데이터 소스나 여러 데이터베이스에 액세스해야 하는 시스템에서는 필연적으로 여러 트랜잭션 관리자가 구성됩니다.

4. @트랜잭션 전파

전파는 7가지 전파 메커니즘을 지원합니다.

필수


비즈니스 메서드는 트랜잭션에서 실행되어야 합니다. 실행 시 메서드가 이미 트랜잭션에 있으면 트랜잭션에 참여하고, 그렇지 않으면 직접 새 트랜잭션을 생성하세요. 이것이 Spring의 기본 전파 동작입니다.


지원:


비즈니스 메서드가 트랜잭션 범위 내에서 호출되면 해당 메서드는 트랜잭션의 일부가 됩니다. 트랜잭션 범위 내에서 호출되면 해당 메서드는 트랜잭션의 일부가 됩니다. 트랜잭션 범위 외부에서 호출되면 해당 메서드는 트랜잭션이 없는 환경에서 실행됩니다.


필수:


비즈니스 메서드가 자체 트랜잭션을 시작할 수 없는 경우에만 실행할 수 있습니다. 트랜잭션이 있고 환경에서 호출되면 예외가 발생합니다.


REQUIRES_NEW


비즈니스 메서드는 항상 자체적으로 새 트랜잭션을 시작합니다. , 메서드가 이미 실행된 경우 트랜잭션에서 원래 트랜잭션이 일시 중지되고 새 트랜잭션이 생성되며 메서드가 종료될 때까지 원래 트랜잭션이 실행을 다시 시작합니다. 🎜>

NOT_SUPPORTED


메서드를 선언하려면 트랜잭션이 필요합니다. 해당 메서드가 트랜잭션과 연결되어 있지 않으면 해당 메서드가 호출되면 컨테이너가 해당 트랜잭션을 열지 않습니다. 거래에서 호출이 완료된 후 원래 거래가 다시 실행됩니다.

절대로:


선언된 메소드는 트랜잭션 범위 내에서 실행되어서는 안 됩니다. 특정 트랜잭션 범위 내에서 메소드가 실행되면 컨테이너는 트랜잭션과 연결되지 않은 경우에만 정상적으로 실행됩니다. 중첩:

          如果一个活动的事务存在,则运行在一个嵌套的事务中.如果没有活动的事务,则按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&#39;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用法详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.