Spring transaction management and Spring transaction management

Source: Internet
Author: User

Spring transaction management and Spring transaction management
I. Transaction overview transaction management is an essential technology for enterprise-level application development. It is used to ensure data integrity and consistency.
A transaction is a series of actions, which are treated as a separate unit of work. These actions are either completed in full or all do not work.
Four key attributes of transactions (ACID)
Atomicity: a transaction is an atomic operation consisting of a series of actions. The atomicity of a transaction ensures that the action is either completely completed or completely ineffective.
Consistency: once all transaction actions are completed, the transaction is committed. data and resources are in a consistent State that meets the business rules.
Isolation: many transactions may process the same data at the same time. Therefore, each transaction should be isolated from other transactions to prevent data corruption.
Durability: Once a transaction is completed, no matter what system error occurs, its results should not be affected. generally, the transaction result is written to the persistent memory. As an enterprise-level application framework, Spring defines an abstraction layer on different Transaction Management APIs. application developers can use Spring's transaction management mechanism without having to understand the underlying transaction management API.
Spring supports both programming and declarative transaction management.
Programmatic Transaction Management: embedding Transaction Management Code into business methods to control transaction commit and rollback. when you compile a program to manage transactions, you must include additional transaction management code in each transaction operation.
Declarative Transaction Management: it is easier to use than programmatic transaction management in most cases. it separates the transaction management code from the business method and implements transaction management in a declarative manner. as a cross-cutting concern, transaction management can be modularized using the AOP method. spring supports declarative transaction management through the Spring AOP framework. spring's Transaction Manager Spring abstracts a complete set of transaction mechanisms from different Transaction Management APIs. developers can use these transaction mechanisms without having to understand the underlying transaction APIs. with these transaction mechanisms, the transaction management code can be independent of specific transaction technologies.
Spring's core transaction management abstraction is platform TransactionManage, which encapsulates a group of technical independent methods for transaction management. no matter which Transaction Management Policy (programmatic or declarative) Spring is used, the transaction manager is required. different implementations of the Transaction Manager in Spring DataSoureTransactionManage: only one data source needs to be processed in the application, and Jta TransactionManage is accessed through JDBC: JTA (Java Transaction API) is used on the JavaEE application server) perform Transaction Management HibernateTransactionManage: Use the Hibernate framework to access the database
......
The transaction Manager uses the @ Transactional annotation to declare transactions in the Spring IOC container in the Bean configuration file with the start point, notification, and enhancement, spring also allows simple annotation of the transaction method with @ Transactional.
To define a method to support transaction processing, add @ Transactional annotation to the method. According to Spring AOP, only public methods can be labeled based on the proxy mechanism.
@ Transactional annotation can be added at the method or class level. When this annotation is applied to the class, all public methods in this class will be defined to support transaction processing.
In the Bean configuration file, you only need to enable the <tx: annotation-driven> element and specify the Transaction Manager for it.
If the transaction processor name is transactionManager, You can omit the transaction-manager attribute in the <tx: annotation-driven> element. This element will automatically detect the transaction processor with this name. @ Transactional
@ Override
Public void purchase (String username, String isbn ){
BookShopDao. updateBookStock (isbn );
BookShopDao. updateUserAccount (username, price );
} <Bean id = "transactionManager" class = "org. springframework. jdbc. datasource. cetcetransactionmanager">
<Property name = "dataSource" ref = "dataSource"> </property>
</Bean>

<! -- 2. Configure transaction properties -->
<Tx: annotation-driven transaction-manager = "transactionManager"/> 2. transaction attributes transaction propagation attributes when the transaction method is called by another transaction method, you must specify how the transaction should be propagated. for example, a method may continue to run in an existing transaction or start a new transaction and run it in its own transaction.
The Propagation Behavior of a transaction can be specified by the propagation attribute. Spring defines 7 types of propagation behaviors. (two are the most common) (1) PROPAGATION_REQUIRED: if a transaction exists, the current transaction is supported. Enable if no transaction exists
(2) PROPAGATION_REQUIRES_NEW: always starts a new transaction. If a transaction already exists, the transaction will be suspended.
(3) PROPAGATION_SUPPORTS: if a transaction exists, the current transaction is supported. If no transaction exists, the transaction is not executed.
(4) PROPAGATION_MANDATORY: if a transaction already exists, the current transaction is supported. If no active transaction exists, an exception is thrown.
(5) PROPAGATION_NOT_SUPPORTED: Always executes non-transactions and suspends any existing transactions.
(6) PROPAGATION_NEVER: Always executes non-transactional operations. If an active transaction exists, an exception is thrown.
(7) PROPAGATION_NESTED: if an active transaction exists, it runs in a nested transaction. if no active transaction exists, press TransactionDefinition. in theory, the isolation level of transactions executed by the PROPAGATION_REQUIRED attribute should be completely isolated from each other to avoid problems caused by concurrent transactions. however, this will have a significant impact on the performance, because the transactions must run in order.
In actual development, transactions run at a lower isolation level to improve performance.
You can specify 1. ISOLATION_DEFAULT: This is the default isolation level of PlatfromTransactionManager. The other four levels correspond to JDBC isolation levels.
2. ISOLATION_READ_UNCOMMITTED: This is the lowest isolation level of the transaction. It allows an external transaction to see the uncommitted data of this transaction. This isolation level will generate dirty reads, which cannot be repeated and Phantom reads.
3. ISOLATION_READ_COMMITTED: ensure that the data modified by one transaction can be read by another transaction only after it is committed. Another transaction cannot read the uncommitted data of the transaction.
4. ISOLATION_REPEATABLE_READ: This transaction isolation level prevents dirty reads and prevents repeated reads. However, phantom reading may occur. In addition to ensuring that one transaction cannot read the uncommitted data of another transaction, it also ensures that the following situations are avoided (non-repeated reads ).
5. ISOLATION_SERIALIZABLE this is the most costly but reliable transaction isolation level. Transactions are processed in sequence. In addition to preventing dirty reads and not repeated reads, Phantom reads are also avoided. The isolation level of transactions must be supported by the underlying database engine, rather than applications or frameworks.
Two transaction isolation levels supported by Oracle: READ_COMMITED and SERIALIZABLE
Mysql supports the transaction isolation level in Mysql 4. By default, only unchecked exceptions (RuntimeException and Error exceptions) will cause transaction rollback.
The rollbackFor and noRollbackFor attributes of the @ Transactional annotation can be used to define the transaction rollback rules. these two attributes are declared as Class [] type, so you can specify multiple exception classes for these two attributes.
RollbackFor: rollback is required
NoRollbackFor: A group of exception classes. In case of a transaction, the rollback timeout and read-only attributes are not required. Because the transaction can obtain a lock on the row and table, long transactions occupy resources and affect the overall performance.
If a transaction only reads data but does not modify it, the database engine can optimize the transaction.
Timeout transaction attribute: how long the transaction can be maintained before forced rollback. This prevents long-running transactions from occupying resources.
Read-Only transaction attribute: indicates that the transaction only reads data but does not update data. This helps the database engine optimize transactions. timeout and read-only attributes can be defined in @ Transactional annotation. the timeout attribute is measured in seconds. in Spring 2.x transaction notifications, timeout and read-only attributes can be specified in the <tx: method> element. <! -- 2. Configure transaction properties -->
<Tx: advice id = "txAdvice" transaction-manager = "transactionManager">
<Tx: attributes>
<! -- Specify the transaction attribute based on the method name -->
<Tx: method name = "purchase" propagation = "REQUIRES_NEW" isolation = "PROPAGATION_REQUIRES_NEW" rollback-for = "java. io. exception "timeout =" 30 "read-only =" true "/> </tx: attributes>
</Tx: advice>

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.