Detailed description of Transaction Management in Spring (focusing on Transaction Manager) and spring transaction
Detailed description of Transaction Management in Spring: Transaction Introduction
Transaction Management is an essential technology in enterprise application development. It is used to ensure data integrity and consistency.
Transactions are a series of actions, which are considered as a separate unit of work. Either all these actions are completed or all of them 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 the 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 satisfies 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 storage.
Transaction Management in Spring
As an enterprise 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 programmatic Transaction Management (also called declarative transactions) and declarative transaction management.
Programmed Transaction Management: Embed the transaction management code into the business method to control the commit and rollback of the transaction. In programming transactions, the additional transaction management code must be included in each business operation.
Declarative Transaction Management: In most cases, it is easier to use than programmed transaction management. 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 Transaction Manager
Spring does not directly manage transactions, but provides a variety of transaction managers that delegate the responsibility of transaction management to the platform-related transaction implementations provided by JTA or other persistence mechanisms. Each transaction manager acts as the facade of the transaction implementation on a specific platform, which makes it almost unnecessary for users to focus on the actual transaction implementation when using transactions in Spring.
Spring provides many built-in Transaction Manager implementations:
- DataSourceTransactionManager:Located in the org. springframework. jdbc. datasource package, the data source Transaction Manager provides the management of a single javax. SQL. DataSource transaction for the transaction management of the Spring JDBC abstract framework, iBATIS, or MyBatis framework;
- JdoTransactionManager:Located in the org. springframework. orm. jdo package, you can manage a single javax. jdo. PersistenceManagerFactory transaction to manage the transaction when integrating the JDO framework;
- JpaTransactionManager:Located in the org. springframework. orm. jpa package, it provides support for a single javax. persistence. EntityManagerFactory transaction and is used to integrate JPA to implement transaction management during the framework;
- HibernateTransactionManager:At org. springframework. orm. in the hibernate3 package. hibernate. sessionFactory supports transaction management when integrating with the Hibernate framework. This Transaction Manager only supports Hibernate3 +, and Spring3.0 + only supports Hibernate 3.2 +;
- JtaTransactionManager:Located in the org. springframework. transaction. jta package, this package provides support for Distributed transaction Management and delegates transaction management to the transaction Manager of the Java EE application server;
- OC4JjtaTransactionManager:Located in the org. springframework. transaction. jta package, the adapter provided by Spring for the OC4J10.1.3 + application server transaction Manager is used to support advanced transactions provided by the application server;
- WebSphere euowtransactionmanager:Located in the org. springframework. transaction. jta package, Spring provides an adapter for the transaction manager of WebSphere 6.0 + application servers. This adapter is used to support advanced transactions provided by the application server;
- WebLogicJtaTransactionManager:Located in the org. springframework. transaction. jta package, Spring provides an adapter for the WebLogic 8.1 + application server transaction Manager. This adapter is used to support advanced transactions provided by the application server.
Spring not only provides these transaction managers, but also provides managers for JMS transaction management. Spring provides consistent transaction abstraction 9-1.
Figure 9-1 Spring Transaction Manager
Next, let's learn how to define the Transaction Manager in the Spring configuration file:
Statement support for local transactions:
A)JDBCAnd iBATIS, MyBatisFramework Transaction Manager
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/></bean>
Use the dataSource attribute to specify a single javax. SQL. DataSource object for transaction management. In the background, cetcetransactionmanager manages transactions by calling java. SQL. Connection, which is obtained through DataSource. Commit a transaction by calling the commit () method of the connection. Similarly, when a transaction fails, the rollback () method is called for rollback.
B)JdoTransaction Manager
<bean id="txManager" class="org.springframework.orm.jdo.JdoTransactionManager"> <property name="persistenceManagerFactory" ref="persistenceManagerFactory"/></bean>
Use the persistenceManagerFactory attribute to specify the javax. jdo. PersistenceManagerFactory object for transaction management.
C)JpaTransaction Manager
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory"/></bean>
You can use the entityManagerFactory attribute to specify the javax. persistence. EntityManagerFactory object for transaction management.
You also need to specify the jpaDialect attribute for the entityManagerFactory object. The object corresponding to this attribute specifies how to obtain the connection object, start the transaction, close the transaction, and other transaction management-related behaviors.
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> …… <property name="jpaDialect" ref="jpaDialect"/></bean><bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
D)HibernateTransaction Manager
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/></bean>
Behind the scenes, HibernateTransactionManagerDelegate the responsibilities of transaction managementOrg. hibernate. Transaction object, which is obtained from the Hibernate Session. When the transaction is completed successfully,HibernateTransactionManagerWill callTransactionObject commit () method to commit transactions. Similarly, when a transaction fails, it is calledTransactionTo roll back.
SpringGlobal Transaction support:
A)JtaTransaction Manager
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"> <jee:jndi-lookup id="dataSource" jndi-name="jdbc/test"/> <bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"> <property name="transactionManagerName" value=" java:comp/TransactionManager"/> </bean></beans>
"DataSource" Bean indicates the data source obtained from JNDI, and txManager is the JTA Transaction Manager. The property transactionManagerName specifies the JNDI name of the JTA Transaction Manager, to delegate the transaction management to the Transaction Manager.
Define transaction attributes
In Spring, declarative transactions are defined by transaction attributes, which describe how transaction policies are applied to methods. Transaction attributes include five aspects. Although Spring provides multiple declarative transaction mechanisms, all methods rely on these five parameters to control how to manage transaction policies. Declarative transactions passPropagation Behavior, isolation level, read-only prompt, transaction timeout and rollback rules.
Propagation Behavior of Spring transactions:
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 seven types of propagation behaviors:
Transaction propagation behaviors supported by Spring
Propagation Behavior |
Description |
PROPAGATION_MANDATORY |
Indicates that the method must be run in the transaction. If the current transaction does not exist, an exception is thrown. |
PROPAGATION_NESTED |
Indicates that if a transaction already exists, this method will run in the nested transaction. Nested transactions can be committed or rolled back independently of the current transaction. If the current transaction does not exist, its behavior is the same as that of PROPAGATION_REQUIRED. Note that the support of various vendors for such promotional activities is different. Check whether they support nested transactions by referring to the Resource Manager documentation. |
PROPAGATION_NEVER |
Indicates that the current method should not run in the transaction context. If a transaction is currently running, an exception is thrown. |
PROPAGATION_NOT_SUPPORTED |
Indicates that the method should not run in the transaction. If the current transaction exists, the current transaction will be suspended during the running of this method. If you use JTATransactionManager, you need to access TransactionManager. |
PROPAGATION_REQUIRED |
Indicates that the current method must run in the transaction. If the current transaction exists, the method runs in the transaction. Otherwise, a new transaction is started. |
PROPAGATION_REQUIRED_NEW |
Indicates that the current method must run in its own transaction. A new transaction will be started. If the current transaction exists, the current transaction will be suspended during the execution of this method. If you use JTATransactionManager, you need to access TransactionManager. |
PROPAGATION_SUPPORTS |
Indicates that the current method does not require the transaction context, but if the current transaction exists, the method will run in this transaction |
PROPAGATION_REQUIRED is the default propagation attribute.
Isolation level of Spring transactions
The isolation level defines the extent to which a transaction may be affected by other concurrent transactions. In a typical application, multiple transactions run concurrently, and the same data is often operated to complete their respective tasks. Concurrency, although required, can cause the following problems.
The problems caused by concurrent transactions can be divided into the following three categories:
①Dirty read (Dirty reads): Dirty read occurs when a transaction reads data that is rewritten by another transaction but has not yet been committed. If the rewrite is rolled back later, the data obtained from the first transaction is invalid.
②Nonrepeatable read): Repeated reads are not allowed when a transaction executes the same query twice or more times, but each time different data is obtained. This is usually because another concurrent transaction updates data during two queries.
③Phantom read): Phantom read is similar to non-repeated read. It occurs when a transaction (T1) reads several rows of data, and another concurrent transaction (T2) inserts some data. In the subsequent query, the first transaction (T1) will find some records that do not exist originally.
Isolation level of Spring transactions
1. ISOLATION_DEFAULT: This is a default isolation level of PlatfromTransactionManager, which uses the default transaction isolation level of the database.
The other four correspond to the JDBC isolation level.
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.
Read-Only of Spring transactions
A read-only transaction is not a mandatory option. It is just a "suggestion", prompting the database driver and database system. This transaction does not include operations to change data, therefore, the JDBC driver and database may perform some specific optimization on the transaction based on this situation. For example, the corresponding database lock is not arranged to reduce the pressure on the database for transactions, after all, transactions consume database resources. "Read-only transactions" is only a recommended configuration for performance optimization, and it is not mandatory for you to do so.
Spring transaction timeout
To make the application run better, the transaction cannot run for too long. Therefore, the fourth feature of declarative transactions is timeout.
Spring transaction rollback rules
By default, transactions will be rolled back only when a runtime exception is encountered, but will not be rolled back when a checkpoint exception occurs, however, you can also declare that the transaction is rolled back as if it encountered a runtime exception in the case of a specific check-type exception. Similarly, you can declare that the transaction will not be rolled back when it encounters a specific exception, even if these exceptions are runtime exceptions.
Article by: http://www.cnblogs.com/longshiyVip/p/5061637.html