Home > Java > javaTutorial > Detailed explanation of examples of Spring's use of annotations for transaction management configuration

Detailed explanation of examples of Spring's use of annotations for transaction management configuration

Y2J
Release: 2017-05-02 11:47:47
Original
1625 people have browsed it

This article mainly introduces Spring's use of annotations for transaction management configuration. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look

Usage steps:

Step 1. Introduce the namespace in the spring configuration file

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 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/tx
 http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
Copy after login

Step 2. Beans with @Transactional annotations are automatically configured to support declarative transactions

<!-- 事务管理器配置, Hibernate单数据源事务 -->
  <bean id="defaultTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
  </bean>
  
  <!-- 使用annotation定义事务 -->
  <tx:annotation-driven transaction-manager="defaultTransactionManager" proxy-target-class="true" />
Copy after login

Step 3.At the declaration of the interface or class, write A @Transactional.

If you only write on the interface, the implementation class of the interface will be inherited. The specific methods of the implementation class of the interface can override the settings at the class declaration

@Transactional //Class-level annotations, applicable to all public methods in the class

Transaction propagation behavior and isolation level

Everyone is using spring When using annotation-based transaction management, you may be a little overwhelmed by the transaction propagation behavior and isolation level. The following is a detailed introduction for easy reference.

Thing annotation method: @Transactional

When marked in front of a class, it indicates that all methods in the marked class perform transaction processing, example:

@Transactional
public class TestServiceBean implements TestService {}
Copy after login

When some methods in the class do not require things:

@Transactional
public class TestServiceBean implements TestService {  
  private TestDao dao;  
  public void setDao(TestDao dao) {
    this.dao = dao;
  }  
  @Transactional(propagation = Propagation.NOT_SUPPORTED)
  public List<Object> getAll() {
    return null;
  }  
}
Copy after login

Thing propagation behavior introduction:

##@Transactional(propagation=Propagation.REQUIRED)


If there is a transaction, then join the transaction, if not, create a new one (by default)


@Transactional(propagation=Propagation.NOT_SUPPORTED)


The container does not open transactions for this method


@Transactional(propagation=Propagation.REQUIRES_NEW)


Regardless of whether a transaction exists, a new transaction is created, and the original one is suspended , after the new execution is completed, continue to execute the old transaction


@Transactional(propagation=Propagation.MANDATORY)


must be executed in an existing transaction, otherwise it will throw Exception


@Transactional(propagation=Propagation.NEVER)


Must be executed in an existing transaction, otherwise an exception will be thrown (opposite to Propagation.MANDATORY)


@Transactional(propagation=Propagation.SUPPORTS)


If other beans call this method and declare transactions in other beans, then use transactions. If other beans are not declared Transaction, then there is no need for transaction.

Thing timeout setting:

@Transactional(timeout=30) //The default is 30 seconds

Transaction isolation level:


@Transactional(isolation = Isolation.READ_UNCOMMITTED)


Read uncommitted data (dirty reads, non-repeatable reads will occur), basically not used


@Transactional(isolation = Isolation.READ_COMMITTED)


Read submitted data (non-repeatable reads and phantom reads will occur)


@Transactional(isolation = Isolation.REPEATABLE_READ)


Repeatable reading (phantom reading will occur)


@Transactional(isolation = Isolation.SERIALIZABLE)


Serialization

MYSQL: Default is REPEATABLE_READ level


SQLSERVER: Default is READ_COMMITTED

Dirty read: One transaction reads to another Uncommitted updated data of the transaction


Non-repeatable read: In the same transaction, the results returned by reading the same data multiple times are different, in other words,


Subsequent reads can read updated data that has been committed by another transaction. On the contrary, "repeatable read" can ensure that the data read is the same when reading data multiple times


in the same transaction. That is, subsequent reads cannot read updated data submitted by another transaction


Phantom reading: One transaction reads insert data submitted by another transaction

Commonly used in @Transactional annotations Parameter description

##readOnlyThis attribute is used to set whether the current transaction is a read-only transaction. Set to true to indicate read-only, and false to indicate read-write. The default value is false. For example: @Transactional(readOnly=true)rollbackForThis attribute is used to set the required rollback Exception class array, when the exception in the specified exception array is thrown in the method, the transaction will be rolled back. For example:

Continued table)

Parameter name

Function description

Specify a single exception class: @Transactional(rollbackFor=RuntimeException.class)

Specify multiple exception classes: @Transactional(rollbackFor={RuntimeException.class, Exception.class})

##propagation #This attribute is used to set the transaction propagation behavior. For specific values, please refer to Table 6-7. isolationThis property is used to set the transaction isolation level of the underlying database. The transaction isolation level is used to handle multi-transaction concurrency. The default isolation of the database is usually used. Level is enough, basically no need to set ittimeoutThis attribute is used to set the timeout seconds of the transaction. The default value is -1 which means never timeout

注意的几点:

1 @Transactional 只能被应用到public方法上, 对于其它非public的方法,如果标记了@Transactional也不会报错,但方法没有事务功能.

2用 spring 事务管理器,由spring来负责数据库的打开,提交,回滚.默认遇到运行期例外(throw new RuntimeException("注释");)会回滚,即遇到不受检查(unchecked)的例外时回滚;而遇到需要捕获的例外(throw new Exception("注释");)不会回滚,即遇到受检查的例外(就是非运行时抛出的异常,编译器会检查到的异常叫受检查例外或说受检查异常)时,需我们指定方式来让事务回滚 要想所有异常都回滚,要加上 @Transactional( rollbackFor={Exception.class,其它异常}) .如果让unchecked例外不回滚: @Transactional(notRollbackFor=RunTimeException.class)

如下:

 @Transactional(rollbackFor=Exception.class) //指定回滚,遇到异常Exception时回滚
public void methodName() {
 throw new Exception("注释");

 }
 @Transactional(noRollbackFor=Exception.class)//指定不回滚,遇到运行期例外(throw new RuntimeException("注释");)会回滚
public ItimDaoImpl getItemDaoImpl() {
 throw new RuntimeException("注释");
 }
Copy after login

3、@Transactional 注解应该只被应用到 public 可见度的方法上。 如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 注解,它也不会报错, 但是这个被注解的方法将不会展示已配置的事务设置。

4、@Transactional 注解可以被应用于接口定义和接口方法、类定义和类的 public 方法上。然而,请注意仅仅 @Transactional 注解的出现不足于开启事务行为,它仅仅 是一种元数据,能够被可以识别 @Transactional 注解和上述的配置适当的具有事务行为的beans所使用。上面的例子中,其实正是 元素的出现 开启 了事务行为。

5、Spring团队的建议是你在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。你当然可以在接口上使用 @Transactional 注解,但是这将只能当你设置了基于接口的代理时它才生效。因为注解是 不能继承 的,这就意味着如果你正在使用基于类的代理时,那么事务的设置将不能被基于类的代理所识别,而且对象也将不会被事务代理所包装(将被确认为严重的)。因 此,请接受Spring团队的建议并且在具体的类上使用 @Transactional 注解。

The above is the detailed content of Detailed explanation of examples of Spring's use of annotations for transaction management configuration. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template

Parameter name

Function description

rollbackForClassName

This property is used to set the need for rollback An array of rollover exception class names. When an exception in the specified exception name array is thrown in the method, the transaction will be rolled back. For example:

Specify a single exception class name: @Transactional(rollbackForClassName="RuntimeException")

Specify multiple exception class names: @Transactional (rollbackForClassName={"RuntimeException","Exception"})

#noRollbackFor

This attribute is used to set an array of exception classes that do not require rollback. When an exception in the specified exception array is thrown in the method, the transaction will not be rolled back. For example:

Specify a single exception class: @Transactional(noRollbackFor=RuntimeException.class)

Specify multiple exception classes: @Transactional(noRollbackFor ={RuntimeException.class, Exception.class})

##noRollbackForClassName

This attribute is used to set an array of exception class names that do not require rollback. When an exception in the specified exception name array is thrown in the method, the transaction will not be rolled back. For example:

Specify a single exception class name: @Transactional(noRollbackForClassName="RuntimeException")

Specify multiple exception class names:

@Transactional(noRollbackForClassName={"RuntimeException","Exception"})

For example: @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)