Comprehensive analysis of Spring's programmatic transaction management and declarative transaction management

Source: Internet
Author: User
Tags savepoint

Comprehensive analysis of Spring's programmatic transaction management and declarative transaction management

Before you start about this tutorial

This tutorial will delve into Spring's simple and powerful transaction management capabilities, including programmatic and declarative transactions. By learning this tutorial, you will be able to understand the nature of Spring transaction management and use it flexibly.

Prerequisite

This tutorial assumes that you have mastered the basics of Java and have some knowledge of Spring. You also need to have basic knowledge of transaction management, such as the definition of transactions, the concept of isolation levels, and so on. This article will use these concepts directly without a detailed explanation. In addition, you may want to master the basics of the database, although this is not a must.

System Requirements

To experiment with the tools and examples in this tutorial, the hardware configuration requirements are: systems with at least 512MB of memory (recommended 1GB). The following software needs to be installed:

    • Sun JDK 5.0 or later or IBM Developer Kit for the Java 5 platform version.
    • Spring Framework 2.5. The sample code included with this tutorial has been tested on Spring 2.5.6.
    • MySQL 5.0 or later.

Back to top of page

Spring Transaction Attribute Analysis

Transaction management is critical for enterprise applications. It ensures that every operation of the user is reliable, even if there is an unusual access situation, it will not destroy the integrity of the background data. Like the bank's self-service teller machine, usually can be normal for customer services, but also inevitably encountered during the operation of the machine suddenly failure, at this time, the transaction must ensure that the operation of the account before the failure to take effect, just like the user just did not use a cash machine at all, to ensure that the interests of users and banks are not lost.

In Spring, transactions are defined by the Transactiondefinition interface. The interface contains methods related to transaction properties. As shown in Listing 1:

Listing 1. Main methods defined in the Transactiondefinition interface
public interface Transactiondefinition{int getisolationlevel (); int getpropagationbehavior (); int gettimeout (); Boolean isreadonly ();}

You might wonder why the interface only provides a way to get properties, without providing a way to set properties. In fact, the logic is simple, the settings of the transaction properties are entirely programmer-controlled, so programmers can customize any method of setting properties, and the fields that hold the properties are not required. The only requirement is that when Spring makes a transactional operation, the method provided by invoking the above interface must be able to return the value of the transaction-related property.

Transaction ISOLATION LEVEL

Isolation level refers to the degree of isolation between several concurrent transactions. Five constants representing the isolation level are defined in the Transactiondefinition interface:

    • Transactiondefinition.isolation_default: This is the default value that represents the default isolation level for using the underlying database. For most databases, this value is usually transactiondefinition.isolation_read_committed.
    • Transactiondefinition.isolation_read_uncommitted: This isolation level indicates that one transaction can read data that has been modified by another transaction but has not yet been committed. This level does not prevent dirty reads and non-repeatable reads, so this isolation level is rarely used.
    • Transactiondefinition.isolation_read_committed: This isolation level indicates that a transaction can only read data that has been committed by another transaction. This level prevents dirty reads, which is the recommended value in most cases.
    • Transactiondefinition.isolation_repeatable_read: This isolation level indicates that a transaction can repeatedly execute a query multiple times throughout the process, and that the records returned are the same each time. These new records are ignored even if there are new data that satisfies the query between multiple queries. This level protects against dirty reads and non-repeatable reads.
    • Transactiondefinition.isolation_serializable: All transactions are executed one after the other, so that there is absolutely no possibility of interference between transactions, that is, the level prevents dirty reads, non-repeatable reads, and Phantom reads. However, this will severely affect the performance of the program. This level is not normally used.
Transactional propagation behavior

The so-called transaction propagation behavior is that if a transaction context already exists before the current transaction is started, there are several options to specify the execution behavior of a transactional method. The transactiondefinition definition includes the following constants that represent propagation behavior:

    • transactiondefinition.propagation_required: If a transaction is currently present, the transaction is joined and a new transaction is created if there is no current transaction.
    • transactiondefinition.propagation_requires_new: Creates a new transaction and suspends the current transaction if a transaction is currently present.
    • transactiondefinition.propagation_supports: If a transaction is currently present, the transaction is joined, and if there is no transaction, the operation continues in a non-transactional manner.
    • transactiondefinition.propagation_not_supported: Runs in a non-transactional manner, suspending the current transaction if a transaction is currently present.
    • Transactiondefinition.propagation_never: Runs in a non-transactional manner and throws an exception if a transaction is currently present.
    • transactiondefinition.propagation_mandatory: If a transaction is currently present, the transaction is joined and an exception is thrown if there is no current transaction.
    • transactiondefinition.propagation_nested: If a transaction is currently present, create a transaction to run as a nested transaction for the current transaction, or if there is no current transaction, The value is equivalent to transactiondefinition.propagation_required.

It should be noted here that the previous six transactional propagation behaviors were introduced by Spring from the EJB and shared the same concepts. And propagation_nested is unique to Spring. A propagation_nested-initiated transaction is embedded in an external transaction (if there is an external transaction), at which point the inline transaction is not a separate transaction, it relies on the existence of the external transaction, and only commits the external transaction to cause the internal transaction to be committed. Nested child transactions cannot be submitted separately. If you are familiar with the concept of savepoint (savepoint) in JDBC, then nested transactions are easy to understand, in fact, nested sub-transactions is an application of the savepoint, a transaction can include multiple savepoint, each nested child transaction. Also, a rollback of an external transaction results in a rollback of the nested transaction.

Transaction timeout

The so-called transaction timeout is the maximum time a transaction is allowed to execute, and if the time limit is exceeded but the transaction is not completed, the transactions are automatically rolled back. The value of int in transactiondefinition represents the time-out, in seconds.

Read-only properties of a transaction

A read-only property of a transaction is a read-only operation on a transactional resource or a read-write operation. A transactional resource is a resource that is managed by a transaction, such as a data source, a JMS resource, a custom transactional resource, and so on. If you determine that only transactional resources are read-only, then we can flag the transaction as read-only to improve the performance of transaction processing. A Boolean type in Transactiondefinition that indicates whether the transaction is read-only.

Rollback rules for transactions

Typically, if an unchecked exception (an exception that inherits from RuntimeException) is thrown in a transaction, the transaction is rolled back by default. If no exception is thrown, or if a checked exception is thrown, the transaction is still committed. This is often the way most developers want to handle it, and is the default way to handle it in EJBS. However, we can manually control transactions as needed to commit a transaction when some unchecked exception is thrown, or to roll back a transaction when some checked exception is thrown.

Back to top of page

Spring Transaction Management API Analysis

In the Spring framework, there are about 100 APIs involved in transaction management, the most important of which are three: Transactiondefinition, Platformtransactionmanager, and Transactionstatus. The so-called transaction management, in fact, is "to follow the given transaction rules to commit or rollback operations." The "Given transaction rule" is expressed in Transactiondefinition, "by ... To perform a commit or rollback operation "is represented by Platformtransactionmanager, and Transactionstatus is used to represent the state of a running transaction. To make an inappropriate analogy, the relationship between Transactiondefinition and Transactionstatus is like the relationship between procedure and process.

Transactiondef ...

This interface has been described earlier, and it is used to define a transaction. It contains the static properties of a transaction, such as transaction propagation behavior, time-out, and so on. Spring provides us with a default implementation class: Defaulttransactiondefinition, which is suitable for most situations. If the class does not meet the requirements, you can implement your own transaction definition by implementing the Transactiondefinition interface.

Platformtrans ...

The Platformtransactionmanager is used to perform specific transactional operations. The interface definition is shown in Listing 2:

Listing 2. Main methods defined in the Platformtransactionmanager interface
public interface platformtransactionmanager{  transactionstatus gettransaction (transactiondefinition definition )   throws TransactionException;   void commit (Transactionstatus status) throws TransactionException;   void rollback (Transactionstatus status) throws TransactionException;}

Based on the different persistence APIs or frameworks used at the bottom, Platformtransactionmanager's main implementation classes are as follows:

    • Datasourcetransactionmanager: For data persistence using JDBC and ibatis.
    • Hibernatetransactionmanager: For data persistence using Hibernate.
    • Jpatransactionmanager: For data persistence operations using JPA.
    • In addition there are Jtatransactionmanager, Jdotransactionmanager, Jmstransactionmanager and so on.

If we use JTA for transaction management, we can get a container-managed DataSource through JNDI and Spring Jtatransactionmanager. Jtatransactionmanager does not need to know DataSource and other specific resources, because it will use the global transaction management provided by the container. For other transaction managers, such as Datasourcetransactionmanager, you need to provide the underlying data source as its property, that is, DataSource, when you define it. Corresponding to the Hibernatetransactionmanager is sessionfactory, and Jpatransactionmanager corresponds to Entitymanagerfactory and so on.

Transactionstatus

The Platformtransactionmanager.gettransaction (...) method returns a Transactionstatus object. The returned Transactionstatus object may represent a new or already existing transaction (if there is a qualifying transaction on the current call stack). The Transactionstatus interface provides a simple way to control transaction execution and query transaction state. The interface definition is shown in Listing 3:

Listing 3. Main methods defined in the Transactionstatus interface
Public  Interface transactionstatus{   boolean isnewtransaction ();   void Setrollbackonly ();   Boolean isrollbackonly ();}

Back to top of page

Programmatic transaction management Overview of spring's programmatic transaction management

Prior to the advent of Spring, programmatic transaction management was the only option for POJO-based applications. People with Hibernate know that we need to explicitly invoke BeginTransaction (), commit (), rollback () and other transaction management related methods in code, which is programmatic transaction management. With the transaction management API provided by Spring, we can flexibly control the execution of transactions in code. At the bottom, Spring still delegates transactional operations to the underlying persistence framework for execution.

Programmatic transaction management based on the underlying API

Based on the three core interfaces of Platformtransactionmanager, Transactiondefinition and Transactionstatus, we can do transaction management in a programmatic way. The sample code is shown in Listing 4:

Listing 4. Transaction management sample code based on the underlying API
public class Bankserviceimpl implements Bankservice {private Bankdao bankdao;private transactiondefinition txdefinition ;p rivate platformtransactionmanager Txmanager;......public boolean transfer (Long Fromid, long toid, double amount) { Transactionstatus txstatus = txmanager.gettransaction (txdefinition); Boolean result = false;try {result = Bankdao.transfer (Fromid, toid, amount); Txmanager.commit (txstatus);} catch (Exception e) {result = False;txmanager.rollback (txstatus); System.out.println ("Transfer error!");} return result;}}

The corresponding configuration file is shown in Listing 5:

Listing 5. Transaction management sample configuration file based on the underlying API
<bean id= "Bankservice" class= "Footmark.spring.core.tx.programmatic.origin.BankServiceImpl" ><property Name= "Bankdao" ref= "Bankdao"/><property name= "Txmanager" ref= "TransactionManager"/><property name= " Txdefinition "><bean class=" Org.springframework.transaction.support.DefaultTransactionDefinition ">< Property Name= "Propagationbehaviorname" value= "propagation_required"/></bean></property></bean >

As shown above, we have added two properties to the class: one is a property of type transactiondefinition, it is used to define a transaction, and the other is a property of type Platformtransactionmanager, which is used to perform transaction management operations.

If a method needs to implement transaction management, we first need to start a transaction before the method starts executing, and call the Platformtransactionmanager.gettransaction (...) method to start a transaction. Once the transaction has been created and started, you can begin writing the business logic code and then perform the commit or rollback of the transaction where appropriate.

The Transactiontemplate-based programming transaction management

As you can see from the previous example, this transaction management approach is easy to understand, but the headache is that the code for transaction management is scattered in the business logic code, destroying the original code, and each business method contains a similar boilerplate code for initiating transactions, committing/rolling back transactions. Fortunately, Spring is aware of this and provides a simplified approach, which is a very common template callback pattern for spring in the data access layer. As shown in Listing 6:

Listing 6. Sample code for transaction management based on Transactiontemplate
public class Bankserviceimpl implements Bankservice {private Bankdao bankdao;private transactiontemplate Transactiontemplate;......public Boolean transfer (final long fromid, final long toid, final double amount) {return (Boolea N) Transactiontemplate.execute (new Transactioncallback () {public Object dointransaction (transactionstatus status) { Object result;try {result = Bankdao.transfer (Fromid, toid, amount);} catch (Exception e) {status.setrollbackonly (); result = false; System.out.println ("Transfer error!");} return result;}});}}

The corresponding XML configuration is as follows:

Listing 7. Transactiontemplate-based transaction management sample configuration file
<bean id= "Bankservice" class= "Footmark.spring.core.tx.programmatic.template.BankServiceImpl" ><property Name= "Bankdao" ref= "Bankdao"/><property name= "transactiontemplate" ref= "Transactiontemplate"/></bean >

The Execute () method of the Transactiontemplate has a parameter of type Transactioncallback, which defines a dointransaction () method, which is usually implemented in the form of an anonymous inner class. The Transactioncallback interface and writes the business logic code in its dointransaction () method. You can use the default transaction commit and rollback rules here, so that you do not need to explicitly invoke any transaction-managed APIs in your business code. The Dointransaction () method has a parameter of type Transactionstatus, and we can call the parameter's Setrollbackonly () method at any point in the method to identify the transaction as rolled back to perform a transaction rollback.

According to the default rule, if an unchecked exception is thrown during the execution of the callback method, or if the Transacationstatus.setrollbackonly () method is explicitly called, the transaction is rolled back, or if the transaction execution completes or throws an exception of type checked, Commits the transaction.

The Transactioncallback interface has a sub-interface transactioncallbackwithoutresult that defines a Dointransactionwithoutresult () method in the interface. The Transactioncallbackwithoutresult interface is primarily used in cases where the return value is not required during a transaction. Of course, for cases where the return value is not required, we can still use the Transactioncallback interface and return any value in the method.

Back to top of page

Declarative transaction management Overview of Spring

Spring's declarative transaction management is based on the underlying AOP. The essence is to intercept the method before and after it, and then create or join a transaction before the target method starts, committing or rolling back the transaction according to execution after the target method is executed.

The greatest advantage of declarative transactions is that you do not need to programmatically manage transactions, so that you do not need to mix transaction-managed code in your business logic code, and you can apply transaction rules to business logic by simply making the relevant transaction rule declarations in the configuration file (or through an equivalent label-based approach). Because transaction management is a typical crosscutting logic in itself, it is where AOP comes in. The Spring development team is aware of this and provides simple and powerful support for declarative transactions.

Declarative transaction management was once a highlight of EJB's pride, and now spring has made POJO the same treatment as EJB for transaction management, allowing developers to use a powerful declarative transaction management feature outside of the EJB container, mainly thanks to the Spring-dependent injection container and SPR ing AOP support. The Dependency injection container provides the infrastructure for declarative transaction management, which makes the Bean manageable for the spring framework, while Spring AOP is the direct implementation of declarative transaction management, as shown in Listing 8.

In general, I strongly recommend the use of declarative transactions in development, not only because of its simplicity, but mainly because it makes the pure business code is not contaminated, greatly facilitates the later code maintenance.

The only disadvantage of declarative transactions, compared to programmatic transactions, is that the finer granularity of the latter only works at the method level and cannot be scoped to the code block as a programmatic transaction. But even with this requirement, there are many workarounds, such as the ability to separate code blocks that require transaction management into methods, and so on.

Here's a look at the declarative transaction management capabilities that Spring provides for us.

Based on Transactioninter ... Declarative transaction Management for

Initially, Spring provides the Transactioninterceptor class to implement declarative transaction management functionality. Let's look at the configuration file in Listing 8:

Listing 8. Transactioninterceptor-based transaction management sample configuration file
<beans...>......<bean id= "Transactioninterceptor" class= " Org.springframework.transaction.interceptor.TransactionInterceptor "><property name=" TransactionManager " ref= "TransactionManager"/><property name= "transactionattributes" ><props><prop key= "Transfer" >propagation_required</prop></props></property></bean><bean id= "BankServiceTarget "Class=" Footmark.spring.core.tx.declare.origin.BankServiceImpl "><property name=" Bankdao "ref=" Bankdao "/ ></bean><bean id= "Bankservice" class= "Org.springframework.aop.framework.ProxyFactoryBean" >< Property name= "Target" ref= "Bankservicetarget"/><property name= "Interceptornames" ><list><idref Bean= "Transactioninterceptor"/></list></property></bean>......</beans>

First, we configured a transactioninterceptor to define the related transaction rules, and he has two main attributes: one is TransactionManager, which is used to specify a transaction manager and delegate specific transaction-related operations to it; The Transactionattributes property of the properties type, which is used primarily to define transaction rules, in which each key-value pair, the key specifies the method name, the method name can use a wildcard character, and the value represents the applied transaction property of the corresponding method.

There are more complex rules for specifying the value of a transaction property, which is a daunting thing in Spring. The specific writing rules are as follows:

propagation behavior [, isolation level] [, read-only property] [, timeout property] [does not affect committed exception] [, exception that causes rollback]
    • The propagation behavior is the only property that must be set, others can be ignored, and spring provides us with a reasonable default value.
    • The value of the propagation behavior must begin with "Propagation_", including: Propagation_mandatory, propagation_nested, Propagation_never, Propagation_not_ Supported, propagation_required, Propagation_requires_new, Propagation_supports, a total of seven kinds of values.
    • The value of the isolation level must begin with "Isolation_", including: Isolation_default, isolation_read_committed, isolation_read_uncommitted, ISOLATION_ Repeatable_read, Isolation_serializable, a total of five kinds of values.
    • If the transaction is read-only, then we can specify the read-only property, using "ReadOnly". Otherwise we do not need to set this property.
    • The value of the Timeout property must begin with "Timeout_", followed by a value of type int, indicating the time-out, in seconds.
    • Exceptions that do not affect commits are that, even if these types of exceptions are thrown in the transaction, the transaction is committed normally. You must precede each exception's name with a "+". The name of the exception can be part of the class name. such as "+runtimeexception", "+tion" and so on.
    • The exception that causes the rollback is that when these types of exceptions are thrown in the transaction, the transaction is rolled back. A "-" must precede each exception's name. The name of the exception can be all or part of the class name, such as "-runtimeexception", "-tion", and so on.

Here are two examples:

<property name= "*service" >propagation_required,isolation_read_committed,timeout_20,+abcexception,+ Defexception,-hijexception</property>

The above expression indicates that, for all method names that end with a service, the propagation_required transaction propagation behavior is used, the isolation level of the transaction is isolation_read_committed, the time-out is 20 seconds, and the transaction throws An exception of type Abcexception or defexception is still committed, and the transaction must be rolled back when an exception of type hijexception is thrown. "ReadOnly" is not specified here, indicating that the transaction is not read-only.

<property name= "Test" >PROPAGATION_REQUIRED,readOnly</property>

The above expression indicates that, for all methods named Test, the propagation_required transaction propagation behavior is used, and the transaction is read-only. In addition, the default values are used for all other properties. For example, the isolation level and the timeout time use the default value of the underlying transactional resource, and when an unchecked exception occurs, the transaction is rolled back, and the transaction is still committed if a checked exception occurs.

With the transactioninterceptor configured, we also need to configure a proxyfactorybean to assemble the target and advice. This is also typical of Spring AOP practices. The proxy class generated by Proxyfactorybean is the target class that is woven into the transaction management logic. At this point, declarative transaction management is even implemented. We do not do anything with the business code, and all the settings are done in the configuration file, which is the greatest benefit of declarative transactions.

Based on Transactionproxy ... Declarative transaction Management for

The previous declarative transaction is good, but there is a very annoying problem: too many configuration files. We have to configure a Proxyfactorybean for each target object, and while the Transactioninterceptor configuration can be reused through the parent-child Bean, the actual reuse probability is not high, which, in addition to the target object itself, Each business class may need to correspond to three <bean/> configurations, and as the number of business classes increases, the profile becomes larger and the management profile becomes a problem.

To alleviate this problem, Spring provides us with a transactionproxyfactorybean for combining the configuration of Transactioninterceptor and Proxyfactorybean. As shown in Listing 9:

Listing 9. Transactionproxyfactorybean-based transaction management sample configuration file
<beans......>......<bean id= "Bankservicetarget" class= " Footmark.spring.core.tx.declare.classic.BankServiceImpl "><property name=" Bankdao "ref=" Bankdao "/></ Bean><bean id= "Bankservice" class= "Org.springframework.transaction.interceptor.TransactionProxyFactoryBean "><property name=" target "ref=" Bankservicetarget "/><property name=" TransactionManager "ref=" TransactionManager "/><property name=" transactionattributes "><props><prop key=" Transfer "> Propagation_required</prop></props></property></bean>......</beans>

As a result, the configuration file is much simpler than before. We call this configuration a Spring classic declarative transaction management. It is believed that developers who use Spring in the early days must be familiar with this way of configuring declarative transactions.

However, the practice of explicitly configuring a Transactionproxyfactorybean for each business class will make the code overly rigid, so we can simplify it by automating the creation of proxies, using the automatic creation of proxies, which are purely AOP knowledge, and readers should refer to the relevant documentation Do not repeat here.

Declarative transaction management based on the <tx> namespace

The first two declarative transaction configuration methods provide the cornerstone of Spring declarative transaction management. Based on this, Spring 2.x introduces the <tx> namespace, combined with the use of <aop> namespaces, to give developers a new experience of configuring declarative transactions, which makes configuration simpler and more flexible. Also, declarative transactions become more powerful, thanks to the pointcut expression support of the <aop> namespace.

As shown in Listing 10:

Listing 10. <tx>-based transaction management sample configuration file
<beans......>......<bean id= "Bankservice" class= " Footmark.spring.core.tx.declare.namespace.BankServiceImpl "><property name=" Bankdao "ref=" Bankdao "/>< /bean><tx:advice id= "Bankadvice" transaction-manager= "TransactionManager" ><TX:ATTRIBUTES><TX: Method Name= "Transfer" propagation= "REQUIRED"/></tx:attributes></tx:advice><aop:config>< Aop:pointcut id= "bankpointcut" expression= "Execution (* *.transfer (..))" /><aop:advisor advice-ref= "Bankadvice" pointcut-ref= "Bankpointcut"/></aop:config>......</beans >

If the default transaction properties meet the requirements, then the code is reduced to the following as shown in Listing 11:

Listing 11. Simplified <tx>-based transaction management sample configuration file
<beans......>......<bean id= "Bankservice" class= " Footmark.spring.core.tx.declare.namespace.BankServiceImpl "><property name=" Bankdao "ref=" Bankdao "/>< /bean><tx:advice id= "Bankadvice" transaction-manager= "TransactionManager" ><AOP:CONFIG><AOP: Pointcut id= "bankpointcut" expression= "Execution (**.transfer (..))" /><aop:advisor advice-ref= "Bankadvice" pointcut-ref= "Bankpointcut"/></aop:config>......</beans >

Because tangent expressions are used, we do not need to create a proxy object for each business class. Also, if the name of the configured transaction manager Bean is "TransactionManager", then we can omit the Transaction-manager property of <tx:advice> because the default value for this property is " TransactionManager ".

Declarative transaction management based on @Transactional

In addition to the namespace-based transaction configuration, Spring 2.x introduces a Annotation-based approach, mainly involving @transactional annotations. @Transactional can be used on interfaces, interface methods, classes, and class methods. When used on a class, all public methods of the class will have transactional properties of that type, and at the method level we can also use the callout to override the class-level definition. As shown in Listing 12:

Listing 12. @Transactional-based transaction management sample configuration file
@Transactional (propagation = propagation.required) Public boolean transfer (long Fromid, long toid, double amount) {return Bankdao.transfer (Fromid, toid, amount);}

Spring uses beanpostprocessor to handle annotations in the bean, so we need to make the following declaration in the configuration file to activate the post-processing bean, as shown in Listing 13:

Listing 13. Enable post-processing bean configuration
<tx:annotation-driven transaction-manager= "TransactionManager"/>

Similar to the previous, the default value of the Transaction-manager property is TransactionManager, which can be omitted if the name of the transaction manager Bean is the value.

Although @Transactional annotations can be used on interfaces, interface methods, classes, and class methods, the Spring team does not recommend using this annotation on an interface or interface method, because it takes effect only when using an interface-based proxy. In addition, @Transactional annotations should only be applied to the public method, which is determined by the nature of Spring AOP. If you use @Transactional annotations on protected, private, or default visibility methods, this is ignored and no exceptions are thrown.

The <tx> namespace and @Transactional-based transaction declaration approach have advantages and disadvantages. The advantage of the <tx>-based approach is that it combines with the pointcut expression and is powerful. With pointcut expressions, a configuration can match multiple methods, and @Transactional-based approach must be annotated with @Transactional on every method or class that needs to use the transaction, although the rules for most transactions may be consistent, but Transactional, it is also not reusable and must be specified individually. On the other hand, the use of @Transactional-based approach is simple and straightforward, with no learning costs. Developers can choose one or both of these options as needed, or even mix them as needed.

If you are not maintaining the legacy code, it is not recommended to use Transactioninterceptor-based and Transactionproxyfactorybean-based declarative transaction management, but learning these two approaches is very beneficial to understanding the underlying implementation.

Although the above list of four types of declarative transaction management, but this division is only for the sake of understanding, in fact, the implementation of the background is the same, but the way users use different.

Back to top of page

Conclusion

The knowledge points in this tutorial are summarized as follows:

    • Programmatic transaction management based on Transactiondefinition, Platformtransactionmanager, and Transactionstatus is the most primitive way Spring provides, and we don't usually write that But understanding this approach has a great effect on understanding the nature of Spring's transaction management.
    • Transactiontemplate-based, programmatic transaction management is the encapsulation of the previous approach, making coding simpler and clearer.
    • Transactioninterceptor-based declarative transactions are the basis of spring declarative transactions and are not generally recommended, but as before, understanding this approach has a significant effect on understanding Spring declarative transactions.
    • Transactionproxyfactorybean-based declarative transactions are an improved version of the Chinese-style, simplified configuration file writing, which is a declarative transaction management approach recommended by spring in the early days, but is not recommended in Spring 2.0.
    • Declarative transaction management based on <tx> and <aop> namespaces is the current recommended approach, with the greatest feature of combining Spring AOP with the strong support of pointcut expressions to make management transactions more flexible.
    • The @Transactional-based approach simplifies declarative transaction management to the extreme. Developers simply add a line to the configuration file to enable the configuration of the related post-processing Bean, and then use the @Transactional to specify transaction rules on methods or classes that need to implement transaction management to achieve transaction management, and do not have the same functionality in other ways.

Comprehensive analysis of Spring's programmatic transaction management and declarative transaction management

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.