Learn spring must-learn Java Fundamentals (7)----Transaction Basics

Source: Internet
Author: User

quoted to learn the spring framework of the technical insider, you must master some basic Java knowledge, is the so-called "ascend will inferiority, involving far must from you." The following Java knowledge is closely related to the spring framework, and it's important to learn (I'll introduce these Java fundamentals through a series that I hope will help you.) ):

[1] Java Reflection knowledge-->spring ioc:http://www.iteye.com/topic/1123081
[2] Java dynamic agent-->spring aop:http://www.iteye.com/topic/1123293
[3] Property editor, Propertyeditor-->spring ioc:http://www.iteye.com/topic/1123628
[4] XML basic knowledge-->spring configuration: http://www.iteye.com/topic/1123630
[5] Annotations-->spring configuration: http://www.iteye.com/topic/1123823
[6] Thread local change, i.e. threadlocal-->spring transaction management: http://www.iteye.com/topic/1123824
[7] Transaction Fundamentals-->spring Transaction Management: http://www.iteye.com/topic/1124043
[8] Internationalization information-->mvc:http://www.iteye.com/topic/1124044
[9] HTTP message-->mvc:http://www.iteye.com/topic/1124408

Spring while providing flexible and convenient transaction management capabilities, these functions are based on the transaction mechanism of the underlying database itself. To gain insight into the transaction management and configuration of spring, it is necessary to learn the basics of database transactions first.

What is a database transaction
A transaction is that multiple operations form a single whole


"
a glory, a loss of loss" This sentence can reflect the idea of business, a lot of complex things to step, but they form a whole, either the whole, or the overall failure. This idea is reflected in the database, which is a number of SQL statements, either all executed successfully, or all execution fails.
database transactions are strictly defined and must meet 4 Properties : atomicity (Atomic ), consistency (consistency ), Isolation (Isolation ) and persistence (Durabiliy ), referred to as acid . The following is a description of each feature.


  • Atomicity: Multiple database operations that make up a single transaction are an indivisible atomic unit, and only all operations succeed, the entire transaction is committed, and any one of the database operations in the transaction fails, and any operations that have already been performed must be revoked to return the database to its original state.
  • consistency: After a successful transaction operation, the database is in a state that is consistent with its business rules, that is, the data is not compromised. If you transfer from account a to account b , no matter if the operation is successful or not,a and b The total amount of the deposit is unchanged.
  • Before the transaction begins, the database is in a consistent state, and after the transaction ends, the database must be in a consistent state.
  • In the case of bank transfers, consistency requires that the execution of the transaction should not change A , B sum of the amounts of two accounts. If there is no such consistency requirement,
  • Money will happen in the course of the transfer, or the phenomenon of missing. A transaction should transition a database from one consistent state to another consistent state.
  • Isolation: In concurrent data operations, different transactions have their own data space, and their operations do not interfere with each other. To be precise, it is not required to be completely non-intrusive, the database specifies a variety of transaction isolation levels, different isolation levels correspond to different degrees of interference, the higher the isolation level, the better the data consistency, but the weaker the concurrency.

    • Persistence: Once the transaction commits successfully, all data operations in the transaction must be persisted to the database, even if the database crashes immediately after committing the transaction, and when the database restarts, it must be able to recover the data through some mechanism.



in these transaction attributes, the data "consistency "is the ultimate goal, other features are measures, requirements or means to achieve this goal.

The database management system generally uses the redo log to ensure atomicity, consistency and persistence, the redo log records each action of the database change, the database executes a part operation in a transaction after the error exits, the database can revoke the operation performed according to the redo log. In addition, for transactions that have already been committed, even if the database crashes, the data that has not been persisted can be re-executed according to the log when the database is restarted.

and JavaThe program adopts the object lock mechanism for thread synchronization, and the database management system uses the database lock mechanism to ensure the isolation of the transaction. When multiple transactions attempt to operate on the same data, only the transaction holding the lock can manipulate the data until the previous transaction completes, and the subsequent transaction has the opportunity to manipulate the data. OracleThe database also uses the mechanism of the data version, where the rollback segment holds a version for each change in the data, so that changes to the data do not affect the reading of the data.

problems with data concurrency

a database may have multiple access clients that can access the database concurrently. The same data in the database may be accessed by multiple transactions at the same time, and if the necessary isolation measures are not taken, it can cause various concurrency problems and destroy the integrity of the data. These problems can be attributed to 5class, including 3class Data read problem (dirty read, non-repeatable read and Phantom Read) and 2class Data Update issues (first class missing updates and second class missing updates). Below, we explain the scenario that caused the problem separately by example.

dirty Reads (Dirty Read)

A
Transaction Read BThe transaction has not yet committed the change data and operates on the basis of this data. If it happens Btransaction Rollback, then athe data read by the transaction is not recognized at all. Look at the dirty read scenario that is raised when the withdrawal transaction and the transfer transaction are concurrent:



in this scenario, Bwant to withdrawAnd then undo the action, and atransfer to the same accountYuan, just because athe transaction reads Btransaction has not yet been submitted, resulting in a loss of accountYuan. In OracleIn the database, dirty reads do not occur.

Reference

a stuttering person in front of the drinks shop counter, the boss warmly greeted up to say: " Drink a bottle? " Stutter hurriedly said:" i ... drink ... drink ... " The boss quickly opened the cans handed to stutter, stuttering finally suppressed his words: " I ... drink ... drink ... I can't afford to drink it! "



non-repeatable read (unrepeatable read)

non-repeatable reading refers to athe transaction reads Bthe change data that the transaction has committed. Suppose ain the course of the withdrawal transaction, Btransfer to this accountYuan, ATwo reads the balance of the account is inconsistent:



in the same transaction, the T4point in time and T7Point-in-time read Account deposit balances are not the same.

Phantom Read (Phantom read)

A
Transaction Read Bwhen a transaction commits a new data, aThe issue of Phantom reads will occur in the transaction. Phantom reading generally occurs in the transaction of calculating statistics, for example, assuming that the banking system is in the same transaction, the total amount of two statistics deposit accounts, in two statistics process, just add a deposit account, and deposited in theMeta, the total amount of two statistics will be inconsistent:



if the new data just satisfies the query criteria of the transaction, the data enters the field of view, resulting in two statistical inconsistencies.

Phantom Read and non-repeatable reading are two confusing concepts, the former refers to other new data that has been committed to the transaction, while the latter refers to the change data (changes or deletions) that have been committed to the transaction, in order to avoid these two situations, the countermeasures are different to prevent reading to the change data, It is necessary to add row-level locks to the operation's data, prevent changes in the data in the operation, and prevent reading to new data, and you will often need to add table-level locks--locks the entire table to prevent new data (Oracleusing multiple versions of data).

first category missing updates

A
when the transaction is revoked, the submitted BThe update data for the transaction is overwritten. This error may cause serious problems, as can be seen through the following account withdrawal transfer:



A
when a transaction is revoked, the "not careful "will bthe transaction has been erased by the amount of money transferred to the account.

category two missing updates

A
Transaction Overwrite Bthe data that the transaction has committed, causing BOffice operations lost:



in the above example, because the cheque transfer transaction covered the withdrawal transaction to the deposit balance of the update, resulting in the bank lost the lastIf the transfer transaction is committed first, the user account will loseYuan.

database lock mechanism

data concurrency can cause a lot of problems, and in some cases some issues are allowed, but in other cases it can be deadly. The database solves the problem of concurrent access through locking mechanism, although different databases differ in implementation details, but the principle is basically the same.

depending on the object being locked, it can be divided into table lock and row lock, which locks the whole table and the latter locks the specific row in the table. From a relationship locked by a concurrent transaction, it can be divided into shared locks and exclusive locks. A shared lock prevents exclusive locking, but allows other shared locks. Exclusive locking prevents other exclusive locks as well as other shared locks. In order to change the data, the database must impose a row exclusive lock on the row where the change was made, INSERT, UPDATE, DELETEand select for UPDATEstatement implicitly takes the necessary row locks. Let's look at Oracledatabase of 5 commonly usedtype of lock.


  • row sharing Lock: generally through SELECT for UPDATE statement implicitly gets a row-sharing lock, Oracle users can also use the LOCK TABLE in ROW SHARE MODE statement to explicitly obtain a row-sharing lock. Row sharing locks do not prevent changes to data rows, but they can prevent other sessions from obtaining exclusive data table locks. Multiple concurrent row and row exclusive locks are allowed, and data table sharing is allowed or shared row exclusive locks are used.
  • Row exclusive Lock: through a INSERT , UPDATE or DELETE statements are implicitly obtained, or through a LOCK TABLE in ROW EXCLUSIVE MODE statement is explicitly obtained. This lock prevents other sessions from acquiring a shared lock, a shared row exclusive lock, or an exclusive lock.
  • table sharing Lock: by LOCK TABLE in SHARE MODE statement is explicitly obtained. This lock prevents other sessions from acquiring row exclusive locks (INSERT,UPDATE , or DELETE), or prevent other tables from sharing row exclusive locks or table exclusive locks, which allow multiple row sharing and table sharing locks in the table. This lock allows the session to have transactional-level access to the table, because other sessions cannot change the locked table until the user commits or backtracking the transaction and frees the lock on the table.
  • table shared Row exclusive: by LOCK TABLE in SHARE ROW EXCLUSIVE MODE statement is explicitly obtained. This lock prevents other sessions from acquiring a table share, row exclusive, or table exclusive lock, which allows other rows to share locks. This lock is similar to a table-sharing lock, except that only one table can be placed on one table at a time for exclusive locking of shared rows. If The A session owns the lock, the B session can perform a SELECT for UPDATE operation, but if b The session tries to update the selected row, you need to wait.
  • table Exclusive: by LOCK TABLE in EXCLUSIVE MODE explicitly obtained. This lock prevents other sessions from any other locks on the table.



Transaction ISOLATION Level

Although the database provides the user with a locked DMLoperation, but the direct use of lock management is very cumbersome, so the database provides users with an automatic lock mechanism. As long as the user specifies the transaction isolation level of the session, the database parses the SQL in the transactionstatement, and then automatically adds the appropriate lock for the data resource for the transaction operation. In addition, the database maintains these locks, and when the number of locks on a resource is too high, automatic lock escalation is performed to improve the performance of the system, which is completely transparent to the user.

Ansi/iso SQL
the standard defines 4Level of transaction isolation, in the same data environment, using the same input, performing the same work, depending on the isolation level, can result in different results. The ability to resolve data concurrency problems at different transaction isolation levels is different, such as table 9-1is shown.



The isolation level of a transaction is opposed to the concurrency of the database, and it grows. In general, use the Read uncommitedThe isolation level of the database has the highest concurrency and throughput, while using the serializableMinimum database concurrency at the isolation level.

SQL
Define Read uncommitedprimarily to provide non-blocking read capability, OracleAlthough read uncommited is also supported, but it does not support dirty reads because Oracleusing a multi-version mechanism to completely resolve the problem of reading dirty data during non-blocking reads and ensuring read consistency, the Oraclethe Read COMMITTEDThe isolation level has satisfied SQLStandard repeatable READisolation level.

SQL
recommended use of repeatable READto ensure that the data is read consistent, but the user can choose the appropriate isolation level according to the needs of the application.

JDBC
Support for Transactions

not all databases support transactions, even if the database that supports the transaction does not support all transaction isolation levels, the user can pass the Connection#getmetadata ()method Get DatabaseMetaDataobject, and through the object's Supportstransactions (), Supportstransactionisolationlevel (intlevel)method to view the transaction support of the underlying database.

Connection
automatically committed by default, which is the SQL that is executed for eachcorresponds to a transaction, in order to be able to add multiple SQLas a transaction execution, you must first pass Connection#setautocommit (false)Block Connectionautomatically submitted and available via Connection#settransactionisolation ()set the isolation level of the transaction, Connectiondefines the corresponding SQLStandard 4A constant of the transaction isolation level. by Connection#commit ()commit a transaction through Connection#rollback ()rolls back the transaction. The following is a typical JDBCcode for transactional data manipulation:

Code Listing 9-1 JDBCTransaction Code

Java Code

  1. Connection Conn;
  2. Try {  
  3. Conn = drivermanager.getconnection ();//① Get Data connection   
  4. Conn.setautocommit (false);//② to turn off autocommit mechanisms   
  5. conn.settransactionisolation (connection.transaction_serializable);//③ SET TRANSACTION ISOLATION Level   
  6. Statement stmt = Conn.createstatement ();
  7. int rows = Stmt.executeupdate ("INSERT into T_topic VALUES (1, ' Tom ')");
  8. rows = Stmt.executeupdate ("UPDATE t_user set topic_nums = topic_nums +1" +
  9. "WHERE user_id = 1");
  10. conn.commit ();//④ Commit a transaction   
  11. }catch (Exception e) {
  12. ...
  13. Conn.rollback ();//⑤ rolling back a transaction   
  14. }finally{
  15. ...
  16. }



in the JDBC 2.0 , a transaction can end up with only two actions: Commit and rollback. However, some applications may need more control over transactions than simply committing or rolling them back. The JDBC 3.0(JDK 1.4 and later versions) introduces a new savepoint feature, which allows the user to split transactions into multiple stages, allowing the user to specify a rollback to a specific savepoint of the transaction. Instead of just rolling back to the point where the transaction started, as in JDBC 2.0, 9-1 shows.



The following code uses the function of the savepoint to roll back to the specified savepoint when a specific problem occurs, rather than rolling back the entire transaction, such as the Code listing 9-2 as shown:

Code Listing 9-2 transaction code using the save point

Java Code

  1. ...
  2. Statement stmt = Conn.createstatement ();
  3. int  rows = stmt.executeupdate ("INSERT into T_topic VALUES (1, ' Tom ')");
  4. savepoint svpt = Conn.setsavepoint ("SavePoint1");//① set up a save point   
  5. rows = Stmt.executeupdate ("UPDATE t_user set topic_nums = topic_nums +1" +
  6. "WHERE user_id = 1");
  7. ...
  8. //② Roll back to ① at the SavePoint1 , ① before the SQL Commit after the entire transaction has been committed,   
  9. // but ① to the ② between the SQL the operation was revoked.   
  10. Conn.rollback (SVPT);
  11. ...
  12. conn.commit ();//③ Commit a transaction   



not all databases support the Save Point feature, and users can databasemetadata#supportssavepoints () method to see if support is supported.

Learn spring must-learn Java Fundamentals (7)----Transaction Basics

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.