Illustrations & Javaweb: Business must be known

Source: Internet
Author: User

Illustrations & Javaweb: Business must be known

Reprinted from http://www.bysocket.com/

Affairs, the familiar Affairs (Transaction), 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) atomicity

Atoms are the smallest units of matter, that is, 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?

1 BEGIN TRANSACTION;2  3 INSERT  into' test '. ' City ' (' state ', ' country ', ' name ')4  5 VALUES6  7('1',' China',' China','Error statement has more than one value');8  9 INSERT  into' test '. ' City ' (' state ', ' country ', ' name ')Ten   One VALUES A   -('1',' China',' China'); -   the 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) Persistence

The 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, and 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 transfer from Brother Yong blog

Dirty read: A transaction reads the uncommitted change data of the B transaction. 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.

Time Transaction A (Deposit) Transaction B (Withdrawal)
T1 Start a transaction
T2 Start a transaction
T3 Enquiry Balance (1000 RMB)
T4 Withdraw 1000 yuan (balance 0 yuan)
T5 Enquiry Balance (0 RMB)
T6 Undo transaction (Balance restored to $1000)
T7 Deposit $500 (balance $500)
T8 Commit a 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.

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:

1  Public classTransactionlevelsextendsBASEJDBC {2      Public Static voidMain (string[] args) {3         Try {4             //Load Database driver5 Class.forName (DRIVER);6             //Database Connection7Connection conn =drivermanager.getconnection (url,user,pwd);8             //Database meta Data9DatabaseMetaData MetaData =Conn.getmetadata ();Ten   One             //whether the transaction is supported A             BooleanIssupport =metadata.supportstransactions (); - System.out.println (issupport); -             //whether the supported transactions the             BooleanIssupportlevel =Metadata.supportstransactionisolationlevel (connection.transaction_serializable); - System.out.println (issupportlevel); -             //Get default transaction -             intDefaultisolation =metadata.getdefaulttransactionisolation (); + System.out.println (defaultisolation); -   +             /**To close a database connection*/ A             if(Conn! =NULL) { at                 Try { - conn.close (); -}Catch(SQLException e) { - e.printstacktrace (); -                 } -             } in}Catch(Exception e) { - e.printstacktrace (); to         } +   -     } the}

The 5th, 7 lines are connected to the database

Line 9th: Get database metadata, which contains database connection information

Line 12th: From the metadata, determine whether the transaction is supported

Line 15th: From the metadata, determine whether the transaction level is supported Transaction_serializable

Line 18th: Here you can see that the default supported transaction level for MySQL is read_committed, which will isolate dirty reads by default.

The specific source code is as follows:

Therefore, in the case of low security requirements and support for 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.