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

May 02, 2017 am 11:47 AM
java spring

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles

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)