Spring Transaction Management----------Integrated Learning Edition

Source: Internet
Author: User

The first to learn without a priority

Spring provides first-class transaction management. Declarative transactions and programmatic transactions can be supported in spring.

A brief introduction to spring

1 Spring's transactions
Transaction management plays a critical role in the application: it is a unit of work that consists of a series of tasks, in which all tasks must be executed simultaneously. They have only two possible execution results, either all of the tasks succeed or all of the tasks fail.
Spring provides rich transaction management capabilities that exceed EJBs and support declarative transactions like EJBS, and it is important that spring provides consistent transaction management with the following benefits.
(1) Provide a consistent programming pattern for APIs of different transactions
(2) provides simpler, easier-to-use programmatic transaction management
(3) Support Spring Declaration transactions
(4) Integration of spring image for data access

2 ACID properties of the transaction
Transactions use the Acid attribute to measure the quality of a transaction. Introduced as follows:
(1) atomicity
The transaction must be atomic, and at the end of the transaction, all tasks in the transaction must complete successfully, or all fail, and the transaction rolls back to the state between the start of the transaction.
(2) Consistency
Transactions must be guaranteed to be consistent with the database, that is, all data in the database and the reality. If the transaction fails, the data must be returned to the state before the transaction executes, whereas the data and the synchronization of the reality are modified.
(3) Isolation
Isolation is a barrier between transactions and transactions, and each transaction must be isolated from the execution results of other transactions until the transaction is executed, guaranteeing that any data accessed by the transaction is not affected by the results of other transactional executions. Isolation not only guarantees that multiple transactions cannot modify the same data at the same time, but also ensures that changes in transaction operations are not visible to another transaction until the change is committed or terminated, and that the concurrent transactions have no effect on each other. This means that all data that is required to be modified or read has been locked in the transaction until the transaction is complete to be freed. Most databases, such as SQL Server and other RDBMS, are isolated by using locks, and each data item or dataset involved in the transaction uses locks to prevent concurrent access.
(4) Durability
If a transaction executes successfully, the persistence of the transaction must ensure that the execution of the transaction is permanent, regardless of any situation in the system.

3 Defects between transactions
There are 3 problems in the transaction that violate the acid return: dirty read, non-repeatable read, and Phantom read line. If more than one concurrent transaction is running, and the transaction operations the same data to complete their task, it can cause 3 problems to be saved. To resolve them, you must define an appropriate isolation level between transactions.
To ensure the integrity of the transaction, there are 3 possible issues that must be resolved between transactions.
(1) Dirty read
When one transaction reads an update that has not yet been committed by another transaction, it is called dirty read. In the case of another transaction rollback, the data of another transaction read by the current firm is invalid. such as: Transaction T1 updated a row of records, has not committed the changes, the T2 read the updated data, and then T1 perform a rollback operation, cancel just the changes, so T2 read the row is invalid, that is, dirty data.
(2) Non-repeatable READ
The same query operation is performed multiple times in a transaction, but the results of each query are different, called non-repeatable reads, usually because the data is modified by another concurrent transaction between two queries. For example, the transaction T1 reads a row of records, and the transaction T2 modifies the record that T1 just read, and then T1 queries again, which is known as non-repeatable reads, unlike the records that were read for the first time.
(3) Phantom line
This is the least of the threats to a transaction, it is similar to non-repeatable reads, and the result of a transaction update affects another transaction issue. But it not only affects the results of another transaction query, but also causes the query statement to return some different rows. For example, the transaction T1 reads a statement that specifies the where condition and returns the result set. At this point the transaction T2 inserts a new row of records that exactly satisfies the T1 's where condition. Then the T1 uses the same criteria to query again, the result set can see T2 inserted records, this new record is fantasy.

Scene Example Link: http://blog.csdn.net/fg2006/article/details/6937413
The 3 problems are: dirty read------non-repeatable---the smallest phantom line.

4 Properties of a transaction
This section focuses on the property description that applies a transaction policy to a method, including the propagation behavior of the transaction, the isolation level of the transaction, the read-only and timeout properties of the transaction.
(1) Communication behavior of the transaction
The propagation behavior is the boundary of the transaction applied to the method, which defines the behavior properties of the transaction, such as the establishment of transactions and pauses.
There are 7 types in spring, with 6 EJB CMT.


*propagation_mandatory:
Specifies that the method must run in a transaction, or an exception will be thrown

*propagation_nested:
Make the method run in a nested transaction, otherwise this property is the same as the Propagation_required property

*propagation_never
Causes the current method to never run in a transaction, or throws an exception

*propagation_not_supported
Defined as a method that is not supported by the current transaction, and the running transaction is paused while the method is running


*propagation_supports
Specifies that the current method supports the current transaction, but does not use a non-transactional method if no transaction is running

*propagation_required_new
The current method must create a new transaction to run, pausing it if an existing transaction is running


*propagation_required
Specifies that the current method must be in a transaction, create a new transaction without a transaction, start with a new transaction and method, and terminate as the method returns or throws an exception

The above definition of spring's propagation behavior in a transaction corresponds to all propagation behavior in the EJB's transaction CMT, where propagation_nested is the transaction propagation behavior defined by spring outside the CMT.
For example:
<property name= "Transactionattributes" >
<props>
<prop key= "query*" >PROPAGATION_REQUIRED,timeout_5,readOnly</prop>
<prop key= "insert*" >PROPAGATION_REQUIRED</prop>
<prop key= "delete*" >PROPAGATION_REQUIRED</prop>
</props>
</property>

(2) Isolation level of the transaction
To resolve the 3 flaws between transactions, you must establish an isolation relationship between transactions to ensure the integrity of the transaction.
Isolation_default
Using the database default isolation level

Isolation_read_uncommitted (read not submitted)
Allowing the read of updates that are not committed by other concurrent transactions can result in 3 defects between transactions, which is the fastest isolation level, but at the same time it has the lowest isolation level


Isolation_committed (Submit Read)
Allows you to read updates that have been committed by other concurrent transactions (against this dirty read), that is, after the statement is committed and after the commit commits the other transaction will be able to read the change. Only data that has been submitted can be read. Most databases, such as Oracle, are this level by default

Isolation_repeatable_read (repeatable reading)
Unless the transaction itself modifies the data, it is mandatory for the transaction to repeat the same data read repeatedly (against this dirty read, non-repeatable read), that is, in the same transaction successively executed the same query statement, the result is the same. The query within the same transaction is the same as the beginning of the transaction, InnoDB the default level. In the SQL standard, this isolation level eliminates non-repeatable reads, but there are also phantom reads


Isolation_serializable (Serial Read)
This is the highest isolation level, which prevents such problems as dirty reads, non-repeatable reads, and Phantom reads, but is completely locked out because of its encroaching data record, causing it to affect the performance of the transaction and become the most slow in the isolation level. The literal translation is "serialization", meaning that the transaction does not allow other transactions to execute concurrently. Fully serialized read, each read need to obtain a table-level shared lock, read and write each other will block


Note: Not all resource managers support all isolation levels, and the above isolation levels can be used for different resource management.



(3) Read-only properties of a transaction
In the operation of the database, the query is the most frequent operation, each time the query is executed from the database to reread the data, and sometimes read the data are the same, such data operations not only wasted system resources, but also affected the system speed. Saving this resource can greatly improve the system speed for large-scale programs.
If a transaction is declared as read-only, the database can optimize the read operation of the transaction based on the nature of the transaction. A read-only property of a transaction needs to be set together with the propagation behavior of the transaction. For example:
<prop key= "query*" >PROPAGATION_REQUIRED,readOnly</prop>

(4) Timeout properties for transactions
This property, like the read-only property of a transaction, needs to be set in conjunction with the propagation behavior of the transaction, which sets the time-out period for the transaction, and the transaction itself may be long without a response for some reason, during which time the transaction may lock the table of the database, which can cause serious performance problems. By setting the time-out period for a transaction, the transaction is rolled back in the specified time-out period, starting from the execution of the transactions. The time-out property of a transaction is defined with a prefix of timeout_ and an integer number, for example:
<prop key= "query*" >PROPAGATION_REGUIRED,timeout_5,readOnly</prop>

+exception indicates that the rollback is performed when the exception is encountered

–exception indicates that when the exception is encountered, no rollback is performed

Common sense knowledge of the second business

11 separate DML will be considered a transaction, even if the begin Transaction,end is not used transaction

2 SQL Server defaults to the readcommitted level, allowing for the latter two concurrency issues.

orcal defaults to the readcommitted level, allowing for the latter two concurrency problems.

The default isolation level for MySQL is repeatable read

3 The isolation between transactions is achieved with locks

4 transactions must be isolated between them and they cannot access to each other. A transaction must use a collection of records that exist in the database at the beginning of the transaction, and should not access the modified collection of other transactions until the end of the transaction.

5 Oracle in the same window, running SQL is the same transaction, so although not committed, but see also changed data.

5 MySQL4.0 can support transactions later, but the MySQL data table is divided into two categories, one is the traditional data table, the other is the data table supporting the transaction. There are two types of data tables that support transactions: InnoDB and BerkeleyDB

Example of a three-database transaction operation

Database Operations Considerations: http://fkl19.blog.163.com/blog/static/45203922201412510159906/

Four Spring transaction configuration

Reference: http://www.cnblogs.com/rushoooooo/archive/2011/08/28/2155960.html

Http://www.blogjava.net/robbie/archive/2009/04/05/264003.html

The spring configuration file about transaction configuration is always composed of three components, namely, DataSource, TransactionManager and agent mechanism of the three parts, regardless of which configuration method, the general change is only the agent mechanism this part.

DataSource, TransactionManager These two parts only according to the data access way change, for example uses Hibernate to carry on the data access, DataSource actually is sessionfactory, The implementation of TransactionManager is Hibernatetransactionmanager.

Structure diagram:

Annotation method:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:     Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring -beans-2.5.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/c Ontext/spring-context-2.5.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/a Op/spring-aop-2.5.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-     Tx-2.5.xsd "> <context:annotation-config/> <context:component-scan base-package=" Com.bluesky "/> <tx:annotation-driven Transaction-manager= "TransactionManager"/> <bean id= "sessionfactory" class= "org.springframework.orm.hibernate           3.LocalSessionFactoryBean "> <property name=" configlocation "value=" Classpath:hibernate.cfg.xml "/>       <property name= "ConfigurationClass" value= "org.hibernate.cfg.AnnotationConfiguration"/> </bean> <!--define the transaction manager (declarative transaction)--<bean id= "TransactionManager" class= "Org.springframework.orm.hibernate3 .     Hibernatetransactionmanager "> <property name=" sessionfactory "ref=" Sessionfactory "/> </bean> </beans>

Note: The @transactional annotation should be added to the DAO at this time, as follows:

Package Com.bluesky.spring.dao;import Java.util.list;import Org.hibernate.sessionfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.orm.hibernate3.support.hibernatedaosupport;import org.springframework.stereotype.Component; Import Com.bluesky.spring.domain.User; @Transactional @Component ("Userdao") public class Userdaoimpl extends Hibernatedaosupport implements Userdao {public     list<user> listUsers () {         return this.getsession (). CreateQuery ("from User"). List ();     }           }

Description of common parameters in @Transactional annotations

Parameter name

Function description

ReadOnly

This property is used to set whether the current transaction is a read-only transaction, set to True for read-only, false to read-write, and the default value to False. Example: @Transactional (readonly=true)

Rollbackfor

This property is used to set an array of exception classes that need to be rolled back, and when the method throws an exception in the specified exception array, the transaction is rolled back. For example:

Specify a single exception class: @Transactional (Rollbackfor=runtimeexception.class)

Specify multiple exception classes: @Transactional (Rollbackfor={runtimeexception.class, Exception.class})

Continuation form)

Parameter name

Function description

Rollbackforclassname

This property is used to set an array of exception class names that need to be rolled back, and when the method throws an exception in the specified exception name array, the transaction is rolled back. For example:

Specify a single exception class name: @Transactional (rollbackforclassname= "RuntimeException")

Specify multiple Exception class names: @Transactional (rollbackforclassname={"RuntimeException", "Exception"})

Norollbackfor

This property is used to set an array of exception classes that do not need to be rolled back, and when a method throws an exception in the specified exception array, the transaction is not rolled back. For example:

Specify a single exception class: @Transactional (Norollbackfor=runtimeexception.class)

Specify multiple exception classes: @Transactional (Norollbackfor={runtimeexception.class, Exception.class})

Norollbackforclassname

This property is used to set an array of exception class names that do not need to be rolled back, and when a method throws an exception in the specified exception name array, the transaction is not rolled back. For example:

Specify a single exception class name: @Transactional (norollbackforclassname= "RuntimeException")

Specify multiple exception class names:

@Transactional (norollbackforclassname={"RuntimeException", "Exception"})

Propagation

This property is used to set the propagation behavior of a transaction, which can be referenced in table 6-7.

Example: @Transactional (propagation=propagation.not_supported,readonly=true)

Isolation

This property is used to set the transaction isolation level of the underlying database, which is used to handle multi-transaction concurrency, usually using the default isolation level of the database, and does not need to be set

Timeout

This property is used to set the time-out seconds for a transaction, and the default value is 1 to never time out

Note the points:

Note:

(1) @Transactional (propagation=propagation.required)

@Transactional (timeout=30)//default is 30 seconds

@Transactional (isolation = isolation.read_uncommitted)

(2) @Transactional can only be applied to the public method, for other non-public methods, if the tag @transactional will not error, but the method does not have transactional functionality.
(3) With spring transaction manager, Spring is responsible for database open, Commit, rollback. Default run-time exceptions are encountered (the throw new RuntimeException ("comment");) rolled back, that is, the rollback occurs when an exception is encountered that is not checked (unchecked) , while encountering the exception that needs to be caught (the throw new Exception ("comment");) does not roll back, that is, when a check exception is encountered (that is, an exception that is thrown when it is not run-time, the compiler checks for an exception that is called a check exception or a check exception), we specify the way to let the transaction roll To get all the exceptions rolled back, add @Transactional (Rollbackfor={exception.class, other exceptions}). If unchecked exception is not rolled back: @Transactional ( Notrollbackfor=runtimeexception.class) is as follows:

(4) @Transactional annotations should only be applied to the public visibility method. If you use @Transactional annotations on protected, private, or package-visible methods, it will not error, but this annotated method will not show the configured transaction settings.

(5) @Transactional annotations can be applied to interface definitions and interface methods, class definitions, and public methods of classes. Note, however, that only @Transactional annotations appear to be less than the open transaction behavior, which is only a meta-data that can be used to identify @Transactional annotations and the beans that are configured appropriately to have transactional behavior. In the above example, it is actually the presence of the <tx:annotation-driven/> element that opens the transaction behavior.

(6) The spring team's recommendation is that you use @Transactional annotations on specific classes (or methods of classes) rather than on any interface that the class implements. You can certainly use @Transactional annotations on the interface, but this will only take effect if you set up an interface-based proxy. Because annotations are not inherited, this means that if you are using a class-based proxy, the transaction's settings will not be recognized by the class-based proxy, and the object will not be wrapped by the transaction proxy (it will be identified as critical). Therefore, accept the suggestions from the spring team and use @Transactional annotations on specific classes.

Spring Transaction Management----------Integrated Learning Edition

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.