Spring Transaction Getting Started (rpm) Spring Transaction Getting Started

Spring Transaction Getting Started

First, the opening statement

1.1  write text reason  

  Recent study spring framework IoC, AOP, Transaction-related knowledge in the system, ready to write three essays records the learning process of perception. This is the first recorded use of spring Transaction and some principles. The learning process should spring from IoC into AOP and then Transaction, sequential write essays here did not follow the learning path.

1.2  preparation skills

  Learn to use the Java Transaction spring have the best knowledge base, master spring IoC and spring AOP, and the concept of an understanding of various types of database transactions. Of course, these are not a must, if you believe your understanding. I have learned in the spring before the transaction a lot of questions: Why such a database operation after being changed in the transaction, the transaction can be rolled back, the database can not operate like too? Transactions during read and write operations other databases to see what results will not see the full result of the operation of Central African affairs? With these questions, start learning to use the spring it matters.

 

Second, the basic concepts and major interfaces

2.1  Basic Concepts

  Why transaction: applications need to ensure the reliability and integrity of the operation by the user, and some operations must be committed to the database as a set of atomic operation (such as transfer, reduced stock orders, etc.), if one fails, the other operations are also it should not take effect, which is the concept of database transactions (single-process inventory reduction, and then add a single record fails, then the stock should not be cut, so this step should be submitted as a single transaction to the database to ensure data integrity sexual).

  Some properties of transactions: Transactions are some attributes to describe, the most important are the transaction isolation level, propagation properties of transactions, and transaction timeout read-only attribute of the transaction.

  Isolation level: isolation level refers to the degree of influence between the multiple transactions concurrently, each transaction isolated from each other. There are several levels as follows:

       ISOLATION_DEFAULT (the underlying database default isolation level, typically ISOLATION_READ_COMMITTED, this level of transaction can only see the changes that have been submitted to other matters, did not submit the modification is not to be seen, such as reducing inventory operation is complete, the next single is not yet complete, the entire transaction did not submit, then this other transaction isolation level is not reduced inventory to see a successful outcome of the operation, visible only after the entire transaction is committed, this is our usual default isolation level)

       ISOLATION_READ_UNCOMMITTED (data can be read another transaction modified but not yet submitted will result in dirty reads and non-repeatable read, rarely used; such as reducing inventory operation is completed, the transaction will be able to see other inventory is reduced, and if this time the stock just to be reduced to 0, other users may fail on the next one, but if the transaction failed at last, inventory is rolled back, there are likely to be purchased by other users)

       ISOLATION_READ_COMMITTED (read only committed data can prevent dirty reads, or the presence of non-repeatable read)

       ISOLATION_REPEATABLE_READ (can be repeatedly execute a query, and each returned record are the same. There are new data to satisfy the query will be ignored, prevents dirty reads and non-repeatable read. When reduce inventory, has performed other transactions this reduction can not see it? this is too strange. temporarily not clear realization of the principle)

       ISOLATION_SERIALIZABLE (turn-by-transaction execution)

  Read consistency: the above isolation level is read data returns we are concerned, because writing is certainly to be mutually exclusive and order execution, concurrent write does not exist. The following look at the consistency of read data.

       Dirty read (access and modify a data transaction, not submitted to modification, another transaction can access and use the data; inventory was reduced, but not single check recorded uncommitted transaction, a read transaction to another stock, found inventory is zero, then the next single failure, at this time if the transaction is rolled back, in fact, inventory is still there, read the dirty data)

       Non-repeatable read (read the same data multiple times within a transaction, between these, another transaction modifies the data, resulting in a transaction the two read data are not the same; the two reads stock, intermediate stock is modified)

       Magic Reading (transaction is not executed independently after the first transaction to modify the data table, the second table also modified transaction data, then the first transaction is inconsistent with the expected data found in the table; if the first transaction Less inventory fails, the second transaction increased inventory, the first transaction somehow find inventory changes, to prevent phantom reads can only be performed with the isolation level serial)

  Propagation properties: When a transaction starts, a transaction context already exists, then the execution behavior may specify a transactional approach.

       PROPAGATION_REQUIRED (there are added, if any, new)

       PROPAGATION_REQUIRES_NEW (New Transaction, before the pending transaction)

       PROPAGATION_SUPPORTS (there is added, there is no way to run a non-transactional places)

       PROPAGATION_NOT_SUPPORTED (There is currently pending transaction)

       PROPAGATION_NEVER (There is throwing an exception)

       PROPAGATION_MANDATORY (there is added, it does not throw an exception)

         PROPAGATION_NESTED (implementation places have nested transactions, External Affairs submitted will trigger an internal transaction commits, external transaction rollback will trigger an internal transaction rollback)

2.2  Main Interface

   The main transaction API :

    TransactionDefinition (business rules: Some property settings affairs, mentioned above, use the default implementation DefaultTransactionDefinition generally meet the requirements, or can extend interface, to achieve its own definition )

    PlatformTransactionManager (transaction management: the Spring does not directly manage the transaction, but the transaction will be entrusted to the JTA persistence mechanism or a particular transaction management platform of responsibility to achieve .spring transaction manager to act as a proxy platform-specific matters, the following figure show )

 

    TransactionStatus (state of affairs: the representative of a new or existing transaction, control transaction execution and query transaction status )

 

Third, programmatic and declarative transaction Affairs

The so-called programmatic transaction is show business writing business logic in code, and declarative transaction is a transaction statement in the configuration file, the code does not affect the basic bean works.

3.1  programmatic transaction

      1) based on the underlying programmatic transaction management API

In this way the direct use PlatformTransactionManager, TransactionDefinition, TransactionStatus three core programming interfaces affairs. The sample code shown in Listing 1:

Listing 1: business logic

Listing 2: The main program

Listing 3: Profile

  As shown in Listing, Example 1 arranged in a three bean (the dataSource data source, and a transaction definition txDefinition transaction manager txManager), transaction program starts at txManager.getTransaction, terminating in txManager.commit (no abnormality during the transaction, transaction is submitted) or txManager.rollback (an exception is thrown during a transaction, the transaction is rolled back). For example, when testing the insertion of two identical transaction data into a database table kv, kv since the key field of the table did the only constraint, the second data inserted will throw an exception, if the transaction is not guaranteed , a database will be inserted into the data, while the second data can not be inserted, is inserted into the affairs example twice, the second time when the insert will throw an exception, the transaction is rolled back, the first data is not real inserted into the database. The preparation of such matters should be noted that where appropriate transaction committed or rolled back.

2) Based on TransactionTemplate of programmatic transaction management

  As can be seen from the above example, there is a lot that way transaction management boilerplate code, such as transaction start, catch the exception, and the way transaction commit transaction rollback, the code severely damaged the structure of the business code, spring to provide an improved programming implement transaction. The sample code shown in Listing 4:

Listing 4: based on business logic implementation TransactionTemplate

Listing 5: Profile

 

   In this way only those packages to TransactionTemplate template code, which is the logic within a TransactionCallback inner class, passed as a parameter txTemplate. The default rule is that during the execution of the callback method throws an unchecked exception or call setRollbackOnly display method, the transaction will be rolled back, otherwise (not throw an exception or throw an exception is caught and does not appear to call setRollbackOnly) to commit the transaction. Such simple way a little more than the underlying API way, but still damage the structure of the business code.

3.2  declarative transaction

         Declarative transaction based on AOP (transaction management itself is a typical cross-section of logic) on top, is essentially a method to intercept, adding the transaction before the beginning of the process after the implementation of the method commit or roll back the transaction according to the situation. The biggest advantage declarative transaction that does not require doping transaction management code in the business logic, only made matters related to the rule declared in the configuration file (recommended for large-scale projects in serious declarative transaction). Shortcoming declarative transaction is a transaction can only be applied to most fine-grained method level.

1) Based on TransactionInterceptor class implements declarative transaction

Listing 6: transaction-based business logic of TransactionInterceptor

Listing 7: Profile

 

   Use declarative transaction configured in this manner, you need to configure a TransactionInterceptor to define the relevant business rules. It includes two properties, one is transactionManager, specify a transaction manager, transactionInterceptor the intercepted transaction-related operations entrusted to it. Another type is Properties transactionAttributes properties, mainly used to define business rules, the specific configuration of this property is not described in detail here. As already mentioned this configuration transaction approach is based on spring AOP can be seen from the class hierarchy TransactionInterceptor in this class is inherited from the Advice interface, familiar spring AOP AOP students should know that in addition to the need to configure Advice also need to assemble a ProxyFactoryBean target and advice, getting proxyFactoryBean instance by spring plants, in fact, the return of the object instance proxyFactoryBean getObject returns, which is woven into the proxy class instance after the transaction management logic of the target class. The realization of the transaction in this way without any operation of the business code, all settings are done in the configuration file. But this way there is a annoying problem: The configuration file is too long. You need to configure a proxyFactoryBean and a transactionInterceptor for each target object, the equivalent for each business class need to configure three bean, with the increase in business class, the configuration file will grow in size, management becomes complicated.

2) based on the declarative transaction management TransactionProxyFactoryBean

  In order to alleviate ProxyFactoryBean achieve declarative transaction configuration complicated issue, spring offers TransactionProxyFactoryBean, the ProxyFactoryBean and packaged into a TransactionInterceptor configuration, other things did not change. Example configured as follows:

Listing 8: TransactionProxyFactoryBean based configuration file

  This configuration is known as spring classic declarative transaction management, although this way than using ProxyFactoryBean and no major improvement, in fact, these two methods have been simple enough to configure declarative transaction.

3) Based on <tx> namespace for declarative transaction management

In front of the two already well used to implement AOP transaction management. In addition, spring also provides an introduction <tx> namespace, used in conjunction with <aop> namespace, gives the developer a new configuration of declarative transactions experience (this is too Che Dan, and means nothing thing).

Listing 9: Based on <tx> namespace transaction management profiles

 

   In this way a little advantage is no need to specify a particular agency is business class, so you only need to configure a reasonable expression of the cut-off point, and then as long as the conditions of the business class will be the proxy.    

4) @Transactional annotation-based declarative transaction management

  Spring is the most convenient configuration of course, is the way annotations, declarative transaction management is no exception, spring acts on the @Transactional annotation interface, the interface methods, classes and class methods generally used on @Transactional in business class public methods, this simple and clear way, no learning costs.

  Overall, these four declarative transaction management is the use of different forms, its implementation is the same as the background.

 

CONCLUSIONS chapter summary

4.1  has encountered a problem

      When using ProxyFactoryBean and TransactionProxyFactoryBean implement declarative transaction management class, he found the transaction does not take effect. It was found that after several exemplary business logic code in the exception process are captured and, with respect for the transaction, business is not thrown, the transaction will be submitted to a data inserted. Remember that you want to capture abnormal release, so that an abnormality is detected and targeted transaction processing transaction processing transactions when using this method.

 

4.2  Knowledge summary

  1) three programming interfaces use transaction.

      2) two programming transaction to achieve, and four declarative transaction implementation.

Guess you like

Origin www.cnblogs.com/williamjie/p/11388757.html