Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use @ transactional in Spring

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

How to use @ transactional in Spring? for this question, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a simpler and easier way.

The implementation steps of @ Transactional annotation management transaction

The implementation steps for managing transactions using @ Transactional annotations are two steps. The first step is to add the transaction configuration information such as listing 1 to the xml configuration file. In addition to using configuration files, the @ EnableTransactionManagement annotation can also enable transaction management. Take a simple DataSourceTransactionManager as an example.

Listing 1. Transaction configuration information in xml configuration

one

two

three

four

five

The second step is to add the @ Transactional annotation to the appropriate method and set the appropriate property information. The attribute information of the @ Transactional annotation is shown in Table 1.

Table 1. Attribute information for @ Transactional annotations

Property name indicates name when there is more than one TransactionManager in the configuration file, you can use this property to specify which transaction manager to select. The propagation behavior of the propagation transaction. The default is REQUIRED. The isolation of isolation transactions. The default is DEFAULT. The timeout for timeout transactions. The default value is-1. If the time limit is exceeded and the transaction has not been completed, the transaction is automatically rolled back. Read-only specifies whether the transaction is read-only. The default value is false;. In order to ignore methods that do not require a transaction, such as reading data, you can set read-only to true. Rollback-for is used to specify the exception types that can trigger a transaction rollback. If there are multiple exception types that need to be specified, they can be separated by commas. No-rollback-for throws the exception type specified by no-rollback-for and does not roll back the transaction.

In addition, @ Transactional annotations can also be added to the class level. When the @ Transactional note is liberated at the class level, it means that all public methods of that class are configured with the same transaction attribute information. See listing 2. All of the methods of the female EmployeeService support transactions and are read-only. When @ Transactional is configured at the class level and @ Transactional is configured at the method level, the application manages the transaction with method-level transaction attribute information, in other words, the method-level transaction attribute information overrides the relevant configuration information at the class level.

Listing 2. Class-level support for @ Transactional annotations

one

two

three

@ Transactional (propagation= Propagation.SUPPORTS,readOnly=true)

@ Service (value = "employeeService")

Public class EmployeeService

At this point, you will find that the implementation steps for managing transactions using the @ Transactional annotation are simple. However, if you do not have a thorough understanding of the transaction management of the @ transaction annotation in Spring, you are prone to errors, such as the problem that the transaction should be rollback without rolling back the transaction. Next, we will first analyze the transaction implementation mechanism of Spring's annotated way, and then list the relevant considerations, in order to finally help developers to accurately and skillfully use Spring transactions.

Transaction implementation mechanism of annotated mode of Spring

When the system calls the target method that declares @ Transactional, Spring Framework uses the AOP proxy by default and generates a proxy object when the code runs. According to the property configuration information of @ Transactional, this proxy object determines whether the target method of the declaration @ Transactional is intercepted by the interceptor TransactionInterceptor. When TransactionInterceptor intercepts, a transaction is created and added before the target method starts execution. And execute the logic of the target method, and finally use the abstract transaction manager (described in figure 2) AbstractPlatformTransactionManager to operate the data source DataSource to commit or roll back the transaction according to whether there is an exception in the execution, as shown in figure 1.

Figure 1. Spring transaction implementation mechanism

There are two kinds of Spring AOP agents: CglibAopProxy and JdkDynamicAopProxy. Figure 1 takes CglibAopProxy as an example. For CglibAopProxy, you need to call the intercept method of DynamicAdvisedInterceptor of its inner class. For JdkDynamicAopProxy, you need to call its invoke method.

As mentioned above, the transaction management framework is provided by the abstract transaction manager AbstractPlatformTransactionManager, while the specific underlying transaction implementation is implemented by the concrete implementation class of PlatformTransactionManager, such as the transaction manager DataSourceTransactionManager. Different transaction managers manage different data resources DataSource, such as DataSourceTransactionManager's Connection for managing JDBC.

The relationship between PlatformTransactionManager,AbstractPlatformTransactionManager and the concrete implementation class is shown in figure 2.

Figure 2. TransactionManager class structure

Notes on the use of annotated transactions

When you have a better understanding of the annotation-based implementation steps of Spring and the internal implementation mechanism of transactions, you will better use annotated transaction management to avoid the problem that data cannot be rolled back when the system throws an exception.

Correctly set the propagation property of @ Transactional

It is important to note that the following three propagation may not start a transaction. The target method was expected to manage the transaction, but if these three propagation are misconfigured, the transaction will not be rolled back.

TransactionDefinition.PROPAGATION_SUPPORTS: if there is a transaction, join it; if there is no transaction, continue to run in a non-transactional manner.

TransactionDefinition.PROPAGATION_NOT_SUPPORTED: runs in a non-transactional manner, suspending the current transaction if there is a current transaction.

TransactionDefinition.PROPAGATION_NEVER: runs in a non-transactional manner, throwing an exception if a transaction currently exists.

Correctly set the rollbackFor property of @ Transactional

By default, if an unchecked exception (an exception inherited from RuntimeException) or Error is thrown in a transaction, Spring rolls back the transaction; otherwise, Spring does not roll back the transaction.

If you throw other types of exceptions in a transaction and expect Spring to roll back the transaction, you can specify rollbackFor. Example:

@ Transactional (propagation= Propagation.REQUIRED,rollbackFor= MyException.class)

By analyzing the Spring source code, we can see that if the exception thrown in the target method is a subclass of the exception specified by rollbackFor, the transaction will also be rolled back.

Listing 3. GetDepth method of RollbackRuleAttribute

one

two

three

four

five

six

seven

eight

nine

ten

eleven

Private int getDepth (Class exceptionClass, int depth) {

If (exceptionClass.getName () .contains (this.exceptionName)) {

/ / Found it!

Return depth

}

/ / If we've gone as far as we can go and haven't found it...

If (exceptionClass = = Throwable.class) {

Return-1

}

Return getDepth (exceptionClass.getSuperclass (), depth + 1)

}

@ Transactional is valid only when applied to the public method

Transaction management can occur only if the @ Transactional annotation is applied to the public method. This is because when using the Spring AOP proxy, before Spring calls the TransactionInterceptor in figure 1 to intercept the target method before and after the execution of the target method, the intercept method of DynamicAdvisedInterceptor (the inner class of CglibAopProxy) or the invoke method of JdkDynamicAopProxy will indirectly call the computeTransactionAttribute method of AbstractFallbackTransactionAttributeSource (through this class Spring gets the transaction attribute configuration property information annotated in Table 1. @ Transactional).

Listing 4. AbstractFallbackTransactionAttributeSource

one

two

three

four

five

Protected TransactionAttribute computeTransactionAttribute (Method method

Class targetClass) {

/ / Don't allow no-public methods as required.

If (allowPublicMethodsOnly () &! Modifier.isPublic (method.getModifiers () {

Return null;}

This method checks whether the modifier of the target method is public. If it is not public, it will not get the property configuration information of @ Transactional, resulting in that TransactionInterceptor will not be used to intercept the target method for transaction management.

Avoid the problem of self-calling AOP of Spring

Under the AOP proxy of Spring, only when the target method is called externally, the target method is managed by the proxy object generated by Spring, which will cause self-calling problems. If other methods in the same class that do not have @ Transactional annotations call methods with @ Transactional annotations, transactions of methods with @ Transactional annotations are ignored and rollback will not occur. See listing 5 as an example of the code.

Listing 5. Examples of self-invocation problems

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

@ Service

-> public class OrderService {

Private void insert () {

InsertOrder ()

}

@ Transactional

Public void insertOrder () {

/ / insert log info

/ / insertOrder

/ / updateAccount

}

}

Although insertOrder has the @ Transactional annotation, it is called by the internal method insert, the transaction is ignored, and the abnormal transaction will not be rolled back.

The above two problems @ Transactional annotations apply only to public methods and self-invocation problems, which are caused by the use of Spring AOP proxies. To solve these two problems, use AspectJ instead of the Spring AOP proxy.

The following AspectJ information needs to be added to the xml configuration information.

Listing 6. Xml configuration information for AspectJ

one

two

three

four

five

six

seven

eight

nine

ten

At the same time, dependency and aspectj-maven-plugin of spring-aspects and aspectjrt are added to the pom file of Maven.

Listing 7. Pom configuration information for AspectJ

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

thirty-two

Org.springframework

Spring-aspects

4.3.2.RELEASE

Org.aspectj

Aspectjrt

1.8.9

Org.codehaus.mojo

Aspectj-maven-plugin

1.9

True

Org.springframework

Spring-aspects

Compile

Test-compile

This is the answer to the question about how to use @ transactional in Spring. I hope the above content can be of some help to you. If you still have a lot of questions to solve, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report