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

Source: Internet
Author: User
Tags sodium

Transferred from: http://www.open-open.com/lib/view/open1414310646012.html

About this tutorial

This tutorial will teach you about Spring's complex, sodium butyrate night-to-day transaction governance functions, including programmatic and declarative transactions. Through the process of this tutorial, you will be able to understand the essence of Spring transaction governance, and the innocent use of it.

Preliminary premise

This tutorial assumes that you are in control of Java Gentigen and have a certain opinion about Spring. You also need to have the common sense of the transaction governance of the root, such as: the definition of transactions, isolation level other concepts, and so on. This article will directly exercise these concepts without doing any specific text. Other, you'd better control the Gentigen of the database, although this is not required.

Sporadic demand

To implement the objects and examples in this tutorial, the hardware setup is equipped with layout requirements: up to 512MB memory (recommended 1GB) sporadic. Requirements to install the following software:

    • 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.
Parsing Spring Transaction Properties

Transaction governance is the key to enterprise application. It guarantees that the user's every operation is reliable, even if the abnormal interview situation, will not damage the integrity of the background data. Just like the bank's self-service teller machine, often day can normal for the customer officer, but also inevitably touch the process of the machine suddenly the shortcomings of the situation, at this time, the transaction must ensure that the shortcomings before the operation of the account does not take effect, just like the user just now complete did not exercise the ATM, in order to guarantee the advantages of users and banks

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

Listing 1. The secondary method of definition in the Transactiondefinition interface
public interface Transactiondefinition{int getisolationlevel (); int getpropagationbehavior (); int gettimeout (); Boolean isreadonly ();}

You may be amazed at why the interface only supplies methods to get properties, not the methods that provide the relevant setting properties. In fact, the affairs are very complex, the setting of the transaction properties is fully mastered by the rail fan, is to be able to customize any set of properties of the method, and the field of the retained attribute does not have any requirements. The only requirement is that when Spring aborts the transaction operation, the method that diverts the above interface supply through the process must be able to value the properties of the previous old transaction.

Transaction ISOLATION LEVEL

Isolation level refers to the level of isolation between several concurrent transactions. The Transactiondefinition interface defines five leakage performance isolation levels other constants:

    • Transactiondefinition.isolation_default: This is the tacit value, the leakage performance exercise the tacit isolation level of the underlying database. For some databases, the constant-day value is transactiondefinition.isolation_read_committed.
    • Transactiondefinition.isolation_read_uncommitted: This isolation level leak shows that one transaction can read data that has been modified by another transaction but has not yet been committed. This level does not avoid dirty reads and impossible repeated reads, which are rarely exercised at this isolation level.
    • Transactiondefinition.isolation_read_committed: This isolation level leak shows that one transaction can only read data that has been committed by one of the other transactions. This level avoids dirty reading, which is the recommended value in most cases.
    • Transactiondefinition.isolation_repeatable_read: This isolation level leak performance A transaction can repeat a query multiple times at the full process side, and each trip to the record is communicated. Even if there is new data between multiple queries to satisfy the query, these new records will be ignored. This level avoids dirty reads and impossible repeated reads.
    • Transactiondefinition.isolation_serializable: All affairs are carried out in turn, so that the whole impossible of the transaction can be annoyed, that is, the level can avoid dirty reading, impossible repetition and phantom reading. But this will seriously affect the effectiveness of the rail. This level is not used in the regular day scenario.
The move of the transaction

The so-called transaction movement means that, assuming that a transaction high context already exists before the first current transaction, there are several options for specifying the action of a transactional method. The transactiondefinition definition includes the following constants that reveal the behavior of the spread:

    • transactiondefinition.propagation_required: Assumes that a transaction is currently present, then involves the transaction, and assumes that there is no transaction at the moment, establishing a new transaction.
    • transactiondefinition.propagation_requires_new: Sets a new transaction, assuming the current transaction exists, suspends the current transaction.
    • Transactiondefinition.propagation_supports: Assumes that a transaction is currently present, then involves the transaction, assuming that there is currently no transaction, running continuously in a non-transactional form.
    • transactiondefinition.propagation_not_supported: Operates in a non-transactional style, suspending the current transaction assuming a transaction is currently present.
    • Transactiondefinition.propagation_never: Runs in a non-transactional style and throws an exception assuming a transaction is currently present.
    • transactiondefinition.propagation_mandatory: If a transaction is currently present, the transaction is involved, and if no transaction is currently present, an exception is thrown.
    • transactiondefinition.propagation_nested: Assuming that a transaction is currently present, a transaction is established as a nested transaction of the current transaction, assuming that there is currently no transaction. The value is equivalent to transactiondefinition.propagation_required.

What needs to be pointed out here is that the following six kinds of transaction moves are Spring's introduction from EJB, they share the concept of communication. And propagation_nested is unique to Spring. A propagation_nested-initiated transaction is embedded in an internal transaction (assuming there is an internal transaction), at which point the inline transaction is not a self-reliant transaction, it relies on the existence of internal transactions, only through the process of internal transaction submission, talent to provoke internal transaction submission, Nested child transactions cannot be committed with zero-D. Assuming familiarity with the concept of retention points (savepoint) in JDBC, nested transactions are carelessly understood, in fact nested sub-transactions are a use of the retention point, a transaction can include multiple retention points, each nested child transaction. Other, a rollback of an internal transaction can also result in a rollback of a nested transaction.

Transaction timeout

The so-called transaction timeout, which is the longest time allowed by an office, assumes that the transaction is automatically rolled back if the time limit is exceeded but the transaction is not completed. In Transactiondefinition, the value of int is leaked to show super-time, its unit is seconds.

Read-only properties of a transaction

A read-only property of a transaction is the abort of a read-only operation or read-write operation on a transactional cost. The so-called transactional costs are those that are governed by transactions, such as data sources, JMS costs, and self-defined transactional costs, and so on. Assuming that only read operations are aborted for transactional costs, we can use transaction notation as read-only to improve the effectiveness of transaction handling. A Boolean type in the transactiondefinition to reveal whether the transaction can be read-only.

Rollback of a transaction delineating politeness

In a constant-day scenario, assuming that an unchecked exception (continuous self-runtimeexception exception) is thrown in the transaction, the tacit consent rolls back the transaction. If no exception is thrown, or if a checked exception is thrown, the transaction is still committed. This regular day is also the most reclamation of the progress of the disposal of the style, but also EJB in the tacit disposition of the style of punishment. We can, however, be able to claim that the wage master transaction commits the transaction when some unchecked exception is thrown, or rolls back the transaction when some checked exception is thrown.

Anatomy of the Spring transaction governance API

In the Spring framework, there are about 100 APIs that touch on transaction governance, the most important of which are three: Transactiondefinition, Platformtransactionmanager, Transactionstatus. The so-called transaction governance, in fact, is "to follow a given transaction to delimit the politeness to commit or rollback operations." The "courtesy of a given transaction" is a manifestation of transactiondefinition leakage, "according to ... To implement commit or rollback operations "is to use Platformtransactionmanager to leak performance, while Transactionstatus is used to reveal the pattern of a running transaction. To make an inappropriate difference, the relationship between Transactiondefinition and Transactionstatus is like the relationship between the track and the process.

Transactiondef ...

This interface has been introduced in the following, it is used to define a transaction. It includes the static properties of transactions, such as: Transaction flow behavior, super-time and so on. Spring has supplied us with a tacit completion class: Defaulttransactiondefinition, which is suitable for most situations. Assuming that the class is not satisfied with the requirements, the process can complete the Transactiondefinition interface to complete my business definition.

Platformtrans ...

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

Listing 2. The secondary method of definition 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;}

The non-durable API or framework that is exercised at the bottom of the voucher, Platformtransactionmanager's secondary completion class extends to:

    • Datasourcetransactionmanager: Applies to scenarios where JDBC and ibatis abort data durability operations.
    • Hibernatetransactionmanager: Applies to the scenario where hibernate aborts data is being used for a durable operation.
    • Jpatransactionmanager: For scenarios where the JPA abort data is being used for a durable operation.
    • Others are Jtatransactionmanager, Jdotransactionmanager, Jmstransactionmanager and so on.

Assuming we exercise JTA abort transaction governance, we can get a DataSource of container governance through process JNDI and Spring's Jtatransactionmanager. Jtatransactionmanager does not need to know DataSource and other specific costs, as it will exercise the global transaction governance of the container supply. For other transaction management, like Datasourcetransactionmanager, in the definition of the need to supply the underlying data source as its properties, that is, DataSource. Corresponding to the Hibernatetransactionmanager is sessionfactory, and Jpatransactionmanager corresponds to Entitymanagerfactory and so on.

Transactionstatus

The Platformtransactionmanager.gettransaction (...) method goes to a Transactionstatus object. The Transactionstatus object that goes to can represent a new or existing transaction (assuming that there is a consistent premise in the current Misappropriation Inn). The Transactionstatus interface provides a complex way to master transaction implementation and query transaction morphology. The interface definition is shown in Listing 3:

Listing 3. The secondary method of definition in the Transactionstatus interface
Public  Interface transactionstatus{   boolean isnewtransaction ();   void Setrollbackonly ();   Boolean isrollbackonly ();}
Programmatic transaction governance Overview of spring's programmatic transaction governance

Before Spring, programmatic transaction governance was the only option for POJO-based use. People who have used Hibernate know that we need to explicitly misappropriate begintransaction (), commit (), rollback () and other transaction governance related methods in code, which is programmatic transaction governance. Through the process Spring supply of the transaction governance API, we can in the code of the innocent grasp of the implementation of the transaction. At the bottom, Spring still vivisystems transaction operations to the underlying durable framework.

Programmatic transaction governance based on the underlying API

Credential Platformtransactionmanager, Transactiondefinition, and Transactionstatus three focus interfaces, we can abort the transaction governance through the process-programmed posture format. The sample code is shown in Listing 4:

Listing 4. Transaction governance 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 Echo settings are equipped with the layout file as shown in Listing 5:

Listing 5. Sample setup for transaction governance based on underlying API with layout file
<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 the Platformtransactionmanager type that implements the transaction governance operation.

Assuming that the method requirement implements transaction governance, we first need to start a transaction before the method is first implemented and misappropriate the Platformtransactionmanager.gettransaction (...) method to start a transaction. Once the transaction has been established and started, the business logic code can be written first, and then the commit or rollback of the transaction is carried out where appropriate.

Programming transaction governance based on Transactiontemplate

Through the example of the process later can be invented, this kind of transaction governance posture is casual negligence understanding, but the headache is that the transaction governance code scattered in the business logic code, damaged the original code of the perceptual, and each business method includes the opposite start transaction, commit/ROLLBACK TRANSACTION boilerplate code. Fortunately, spring also thought of this and supplied a simplified approach, which is the template callback method that spring has in the data interview layer. As shown in Listing 6:

Listing 6. Transactiontemplate-based transaction governance sample code
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 Echo XML settings are equipped with the following layout:

Listing 7. Transactiontemplate-Based Transaction governance sample Setup with layout files
<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 Transactiontemplate has a parameter of type Transactioncallback, which defines a dointransaction () method, which we complete in the form of anonymous inner class. The Transactioncallback interface and writes the business logic code in its dointransaction () method. It is possible to exercise the tacit consent of the transaction submission and rollback to delimit the politeness, so that in the business code there is no need to explicitly misappropriate any transaction governance API. The Dointransaction () method has a parameter of type Transactionstatus, and we can misappropriate the parameter's Setrollbackonly () method anywhere in the method to identify the transaction as a rollback to implement a transaction rollback.

The voucher tacitly defines politeness, assuming that the process that implements the callback method throws an unchecked exception, or explicitly diverts the Transacationstatus.setrollbackonly () method, rolls back the transaction, assumes that the transaction is complete or throws an exception of type checked, Commits the transaction.

The Transactioncallback interface has a sub-interface Transactioncallbackwithoutresult, which defines a dointransactionwithoutresult () method, The Transactioncallbackwithoutresult interface is used primarily for cases where the transaction process is not required to go to a value. Although, we can still exercise the Transactioncallback interface and go to random whims in the method if we do not need to go to the value of the situation.

Declarative transaction governance overview of spring's declarative transaction governance

Spring's declarative transaction governance is based on the Gentigen of AOP on the ground floor. The essence is to isolate the method before it is first set up or intervene in a transaction before the end of the method, and then commit or rollback the transaction after the completion of the intent method.

The most common advantage of declarative transactions is that you do not need to govern transactions through a process-programmed, in-place format, so that you do not require code that is mixed with transaction governance in your business logic code, and you only need to delimit the polite declaration (or the process-equivalent notation-based format) of the transaction involved in setting up the layout file. That is, the business logic can be applied politely. Because the transaction governance itself is an example of the crosscutting logic, it is exactly where AOP comes in. The Spring reclamation team also thought of this, providing a complex and sodium butyrate-night support for declarative transactions.

Declarative transaction governance was once a bright spot for EJB, and now spring allows POJO to have the same treatment as EJB in terms of transaction governance, and the flash reclamation staff is also using the sodium butyrate-night declarative transaction governance function outside the EJB container, thanks to the spring-based injection container and SPR ing AOP support. Relying on the injection container to provide the root Otugen for declarative transaction governance, the Bean is governed by the spring framework, and spring AOP is the direct completion of declarative transaction governance, as can be seen in the process listing 8.

In the case of the constant day, the author vigorously recommended in the reclamation exercise declarative transactions, not only because of its complexity, but also the main assumption because this makes the pure business code is not purified, very much at random later code treasure.

In contrast to programmatic transactions, the only thing that is missing from declarative transactions is that the finer granularity of the latter can only be disseminated to the method level, and cannot be disseminated to the code block level as a programmatic transaction. But even if there is such a demand, there are many workarounds, such as the need to abort the transaction governance of the code block self-reliance as a method and so on.

Let's take a look at the declarative transaction governance functions that Spring supplies for us.

Based on Transactioninter ... Declarative transaction governance for

Initially, Spring supplied the Transactioninterceptor class to implement declarative transaction governance functions. Let's look at the setup for listing 8 with the layout file:

Listing 8. Transactioninterceptor-Based Transaction governance sample Setup with layout files
<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 set up a layout with a transactioninterceptor to define the related transactions to delimit politeness, he has two secondary attributes: One is TransactionManager, which is used to specify a transaction manager and to Vivisystems specific transaction-related operations to it The other one is the Transactionattributes property of the properties type, which is used to define the politeness of the transaction, which specifies the method name for each key-value pair of the property, the method name can exercise the wildcard character, and the value leaks the transaction properties used to represent the Echo method.

Specifying the value of a transaction property has a rather complex delineation of politeness, which is a headache in Spring. The specific writing delineated courtesy of the following:

Stream move [, isolation level] [, read-only property] [, timeout property] [does not affect committed exception] [, resulting in rollback exception]
    • The move is the only required property, others can be neglected, spring provides us with reasonable tacit value.
    • The value of the move must be "propagation_" to open the first, including: Propagation_mandatory, propagation_nested, Propagation_never, Propagation_not_ Supported, propagation_required, Propagation_requires_new, Propagation_supports, a total of seven kinds of values.
    • Isolation level Other values must be "isolation_" to open the first, including: Isolation_default, isolation_read_committed, isolation_read_uncommitted, ISOLATION_ Repeatable_read, Isolation_serializable, a total of five kinds of values.
    • Assuming that the transaction is read-only, we can specify the read-only property, and then the "ReadOnly" is specified. Otherwise we do not need to set this property.
    • The value of the timeout attribute must be opened with "Timeout_", followed by a value of type int, the leak behaves super-time, and the unit is seconds.
    • Exceptions that do not affect commits mean that, even if these types of exceptions are thrown in the transaction, the transaction commits normally. A "+" must be appended to each exception's name. The name of the exception can be a part of the class name. Like "+runtimeexception", "+tion" and so on.
    • The exception that causes rollback is that when these types of exceptions are thrown in a transaction, the transaction is rolled back. You must add "-" after 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 leakage performance, for all method name with Service closure method, the exercise propagation_required transaction flow move, transaction isolation level is isolation_read_committed, super time is 20 seconds, when 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. There is no "readOnly" specified here, and the leak performance transaction is not read-only.

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

The above expression leakage performance, for all methods named Test method, the exercise propagation_required transaction flow behavior, and the transaction is read-only. In addition to this, the other attributes are exercised with tacit value. Like, the isolation level and the super-time to exercise the tacit value of the underlying transactional costs, and when the fire does not check the exception, the rollback of the transaction, the ignition has been checked exception is still committed transaction.

Setup equipped with layout Well transactioninterceptor, we also need to set up with layout a proxyfactorybean to assemble target and advice. This is also the example of Spring AOP practice. The acting class generated by the process Proxyfactorybean is the purpose class that weaves into the transaction governance logic. At this point, declarative transaction governance is done. We do not abort any operations on the operating code, and all settings are done in the Setup provisioning layout file, which is the most advantageous of declarative transactions.

Based on Transactionproxy ... Declarative transaction governance for

The later declarative transaction is good, but there is an unusually annoying accomplishment: there are too many settings with layout files. We must set up a Proxyfactorybean with layout for each target object; Other, although the transactioninterceptor can be set up with layout through the posture of the process parent-child Bean, the ideal reuse probability is not high; Add the target person, each business class can be required to correspond to three <bean/> set equipped with layout, followed by the increase in business, set up with layout files will become more and more heavy, governance settings equipped with layout files has become a success.

To mitigate this achievement, Spring has supplied us with a transactionproxyfactorybean for the Transactioninterceptor and Proxyfactorybean settings to be equipped with layout. As shown in Listing 9:

Listing 9. Transactionproxyfactorybean-Based Transaction governance sample Setup with layout files
<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 such, setting up a layout file with previous comparisons simplifies a lot. We have this type of setup equipped with the layout-style format called Spring Classic declarative Transaction governance. Trust in the late exercise Spring reclamation personnel for this type of Setup with layout declarative transactions must be very familiar with the style.

But, explicitly for each business class set up with layout a Transactionproxyfactorybean practice will make the code appear too mechanical, for this we can exercise automatically set up the acting form to simplify it, exercise automatically set up acting is pure AOP common sense, Please refer to the relevant documents, do not repeat here.

Declarative transaction governance based on <tx> namespaces

The following two declarative transaction settings are equipped with the layout format, which lays the foundation for Spring declarative transaction governance. In this Gentigen, Spring 2.x introduced the <tx> namespace, the contact exercise <aop> namespace, bringing reclamation personnel to set up a new experience with layout declarative transactions, set up with layout become doubly complex and innocent. Other, declarative transactions also become doubly sodium butyrate night, thanks to the pointcut expression support of the <aop> namespace.

As shown in Listing 10:

Listing 10. <tx>-Based Transaction governance sample Setup with layout 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 >

Assuming that the tacit nature of the transaction is satisfied, the code is simplified as shown in Listing 11:

Listing 11. Simplified <tx>-Based Transaction governance sample Setup with layout 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 the tangent expression is exercised, we do not need to set up an acting object for each business class. Other, assuming that the name of the transaction manager Bean with layout is set to "TransactionManager", we can omit the Transaction-manager property of <tx:advice> because the implied value of the property is " TransactionManager ".

Declarative transaction governance based on @Transactional

In addition to the namespace-based transaction setup with the layout format, the Spring 2.x also introduces a Annotation-based, in-place format, with minor touches to the @transactional annotation. @Transactional can be disseminated on interfaces, interface methods, classes, and class methods. When counted on a class, all public methods of that class will have transactional properties of that type, and we can also exercise the callout at the method level to bring up other definitions at the class level. As shown in Listing 12:

Listing 12. @Transactional-Based Transaction governance sample Setup with layout file
@Transactional (propagation = propagation.required) Public boolean transfer (long Fromid, long toid, double amount) {return Bankdao.transfer (Fromid, toid, amount);}

Spring exercises Beanpostprocessor to dispose of annotations in the penalty bean by activating the post-disposition penalty bean as we require in the setup-equipped layout file, as shown in Listing 13:

Listing 13. Enable post-disposition penalty bean settings with layout
<tx:annotation-driven transaction-manager= "TransactionManager"/>

In contrast to the following, the Transaction-manager property's tacit value is TransactionManager, which assumes that the transaction-manager Bean's name is the value, you can omit the attribute.

Although @Transactional annotations can be disseminated on interfaces, interface methods, classes, and class methods, the Spring team does not recommend that annotations be made on the downstream interface or interface methods, because it only takes effect when the interface-based acting is used outside. Other, @Transactional annotations should only be applied to the public method, which is determined by the essence of Spring AOP. Assume that you exercise @Transactional annotations under protected, private, or tacit permission, and this will be negligent and will not throw any exceptions.

The blemishes based on the <tx> namespace and the @Transactional-based transaction declaration form. Based on the <tx> style, the advantage is that it is connected with the pointcut expression and functions sodium butyrate night. The use of a pointcut expression, a setting equipped with layout can be married to multiple methods, and the @Transactional-based format must be in each demand to exercise the method or class of the transaction with @Transactional labeling, although it can be most of the business of the delineation of politeness is not, but to Transactional, also cannot be reused, must be one by one specified. On the other hand, the @Transactional-based style of the form of the exercise is unusually complex and clear, there is no education costs. Reclamation personnel can be voucher requirements, optional one of the exercise, and even can be a voucher requirements of the mix exercise these two forms.

Assuming that the legacy code is not aborted, it is not recommended to exercise the Transactioninterceptor-based and Transactionproxyfactorybean-based declarative transaction governance style, but, Learning these two poses is not conducive to understanding the underlying completion.

Although the above enumeration of four types of declarative transaction governance style, but this division is only for the sake of understanding, in fact, the completion of the backstage format is the same, but the user exercised the style of the same.

Stop language

The common sense points of this tutorial are summarized below:

    • Programming transaction governance based on Transactiondefinition, Platformtransactionmanager, and Transactionstatus is the most primitive form of Spring supply, and we don't write that on a regular day. But the opinion of this kind of style is very hongwen to understand the essence of Spring transaction governance.
    • Transactiontemplate-based programming transaction governance is the encapsulation of the previous style, which makes the coding more complex and complex.
    • Transactioninterceptor-based declarative transactions are the Gentigen of spring declarative transactions, and often do not recommend the use of such poses, but, as in the following, the idea of this type of style is very hongwen for understanding spring declarative transactions.
    • The Transactionproxyfactorybean-based declarative transaction is an improved version of the up-and-down format, with a simplified setup with the writing of the layout file, which is the declarative transaction governance style for late spring referrals, but is not recommended in Spring 2.0.
    • Declarative transaction governance based on <tx> and <aop> namespaces is the style of the present recommendation, the most characteristic of which is the sodium butyrate night support with Spring AOP, which can spare the use of the pointcut expression and make the governance transaction doubly innocent.
    • The @Transactional-based format simplifies declarative transaction governance to the extreme. Reclamation personnel simply add a line in the settings equipped with the layout file to enable related post-disposition of the penalty Bean settings equipped with layout, and then in the requirements of the implementation of transaction management methods or classes under the exercise @Transactional the specified transaction delimited courtesy to complete the transaction governance, and the function does not require other style subtractive.

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.