Illustrations & Javaweb: Business must be known

Source: Internet
Author: User

Affairs, the familiar Affairs (transcation), will basically depend on the spring transaction. In fact, spring transaction management is based on the transaction processing mechanism of the underlying database itself. The foundation of database transactions is the basis for mastering Spring transaction Management. This article summarizes the database transactions.

I. Database transactions

It's thought: we are logging tired. is multiple SQL statements (one team), or all execution success, or fail. Its ultimate goal: the data will not be destroyed. That is, the transaction operation succeeds, and the result of the data is consistent with the result of the business expectation. This is also the consistency in acid (consistency). So what is acid?

Second, ACID

Above is the thought, the cow immediately according to the idea of modeling, DBMS database transactions to meet the 4 characteristics, namely, atomicity, consistency, isolation and durability. Here are one by one vivid explanations: a) atomic atoms are the smallest unit of matter, i.e. no further division. For example, in MySQL, for example, each simple SQL statement is contained in a transaction and is atomic in nature. At this time someone asked, how many SQL?

BEGIN transaction;insert into ' test '. "City" (' state ', ' country ', ' name ') VALUES (' 1 ', ' China ', ' China ', ' ERROR statement more value '); Nsert into ' Test ' "City" (' state ', ' country ', ' name ') VALUES (' 1 ', ' China ', ' China '); COMMIT;

Result: execution does not pass. Line 3-5: For an error SQL. Line 6-8: is a correct SQL. They are each wrapped in their own implicit transaction, the Read uncommited. T-all wraps up the atoms above the T-1 and T-2, realizing larger atoms, such as. b) Consistency ultimate goal: data is not compromised. (This is not nonsense?) Yes, a bit) specifically, 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. For a chestnut: Two update statements, from a account transfer to a B account, regardless of successful failure, the total of A and B accounts is constant. c) Isolation Isolation: indicates non-interference. There is no interference between transactions and transactions, that is, each transaction is independent and does not intersect. This allows multiple threads to access the database concurrently. But the smart little buddy knows that if the transaction is completely isolated , allowing only one transaction to access the database at a time, the other is blocking. will be very slow. But smart little friends know that this can cause concurrency problems with data. (yes, in the third section below). d) Persistent data must be persisted to the database (stored on disk). Committed transactions, even if the database crashes after a commit, and restarts the database to perform a redo of the data that is not persisted based on the log. (The reunion asked, the business that did not submit?) That's tragic. (>﹏<)) Summary: Data consistency is the ultimate goal, other features are their requirements or means.

Iii. problems in isolation: dirty reading, non-repeatable reading, and Phantom reading

Corresponding to the above isolation, transaction concurrent access will occur: dirty read, non-repeatable read and Phantom read. Case to Brother Yong blog Dirty read: A transaction read the B transaction uncommitted change data. The general database transaction does not allow the issue to occur by default. For example, here the query should be 1500, now there is dirty read.

  & nbsp;  
time transaction A (deposit) transaction B (withdrawal)
T1 start transaction  
T2   start Transaction
T3   query Balance (1000 RMB)
T4   Remove 1000 yuan (balance 0 RMB)
T5 query balance (0 RMB)  
T6   undo Transaction (Balance restored to $1000)
T7 Deposit 500 yuan (balance 500 RMB)  
T8 Commit transaction  

Non-REPEATABLE READ: A transaction reads the change data submitted by the B transaction. Phantom READ: A transaction reads the new data submitted by the B transaction.   The above case of brain repair, the main or look at the following. non-REPEATABLE read and Phantom read differences : One change, one new data. In fact, the two difference is that a new (INSERT statement), processing Phantom Read this operation requires a table-level lock, the entire table is locked to prevent new data caused by Phantom read. The other is the change (update delete), which avoids the need to add row-level locks to organize the row to change.

Iv. Transaction ISOLATION LEVEL

High isolation (security) and high concurrency are required. This is an impossible task. A transaction isolation level occurs based on the operation mechanism of various locks. That is, the input in the same case, different isolation level results. Why, of course, is the choice of concurrency and security. According to the diagram, depending on the concurrency of the program and the choice of security. You can't have your cake and eat it too. But distributed, you can. Security-critical individual distributed locks.   Well, the case says a lot of the following code in combat. PS: Rest, the masons code will be on this github ~, this code address: https://github.com/JeffLi1993/jee-component-learning

Five, JDBC transaction actual combat

The following MySQL JDBC driver is used to connect MySQL, the code is as follows:

public class Transactionlevels extends Basejdbc {public static void main (string[] args) {try {//Add Download Database driver            class.forname (DRIVER);            //database connection            connection conn = DriverManager . getconnection (URL,USER,PWD);            //database metadata            databasemetadata metaData = Co Nn.getmetadata ();            //support transaction            boolean issupport = Metadata.s Upportstransactions ();           &NBSP;SYSTEM.OUT.PRINTLN (issupport);            //support transactions            boolean issupportlevel = meta Data.supportstransactionisolationlevel (connection.transaction_serializable);           &NBSP;SYSTEM.OUT.PRINTLN (issupportlevel);       &nbsp    //get default transaction            int defaultisolation = Metadata.getdefaulttransactionisol Ation ();           &NBSP;SYSTEM.OUT.PRINTLN (defaultisolation);                           /** Close Database connection */          &NBSP;IF (conn! = null) { try {conn.close ()                } catch (Sqlexcept        Ion e) {e.printstacktrace ()                }} } catch (Exception e) {e.printstacktrace ();        }}}

Line 5th, row 7 is connected to the database 9th row: Get the database metadata, which is the database connection information is included in line 12th: from the metadata, determine whether to support transaction 15th row: From the metadata, determine whether to support transaction level transaction_serializable 18th line: Here you can See that the default supported transaction level for MySQL is read_committed, which isolates dirty reads by default. The specific source code is as follows: Therefore, in the case of low security requirements, support high concurrency, select MySQL default transaction level. However, in the case of high security, there is very little concurrency and a higher transaction level is chosen. It is clear from the picture in the previous section.

Vi. Supplementary

About the transaction, as well as familiar with the spring transaction management, the implementation of specific database transactions, recommended a book "MySQL Technology insider InnoDB storage engine." Next: threadlocal working mechanism, revealing how the Spring transaction Synchronization Manager works if the above articles or links are helpful to you, don't forget to share the circle of friends and let more people read this article.

Illustrations & Javaweb: Business must be known

Related Article

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.