Java programmers from stupid birds to cainiao () Talk about hibernate (16) database transactions and isolation level

Source: Internet
Author: User



Database transactionsTransaction refers to a group of mutually dependent operations, such as bank transactions, stock transactions, or online shopping. The success of a transaction depends on whether these mutually dependent operations can be successfully executed. If one operation fails, the entire transaction fails. A typical example of a transaction is that a transfers the money from the bank to the Account B. The transaction includes the following operations:

(1) deduct 100 yuan from a's account.

(2) Add RMB 100 to B's account.

Obviously, the above two operations must be an inseparable unit of work. If the first operation is successful and Tom's account is deducted 100 yuan, but the second operation fails and Jack's account does not increase 100 yuan, the entire transaction fails. A database transaction is a simulation of transactions in real life. It is composed of a group of SQL statements that depend on each other in the business logic.

Let's take a look at it.Lifecycle of database transactions:


The lifecycle diagram of the Database Transaction reflects the three boundaries of the database transaction:

1. Start boundary of the transaction.

2. normal transaction termination boundary (COMMIT): commit a transaction and permanently Save the database Status updated by the transaction.

3. rollback: cancels the transaction and returns the database to the initial state before the transaction is executed.

In fact, each database connection has a global variable @ autocommit, indicating the current transaction mode. It has two optional values: 0, indicating the manual commit mode. 1: default value,Indicates the automatic submission mode.

In the automatic commit mode, each SQL statement is an independent transaction. That is to say, the database automatically submits this transaction every time an SQL statement is executed. When we use another database client to query the transaction, we can see the newly modified or inserted data.In manual submission Mode, The transaction start boundary and end boundary must be explicitly specified:

-Start boundary of the transaction: Begin

-Commit transaction: commit

-Undo transaction: rollback

Let's take a look at it.How to declare the transaction boundary through the jdbc api:

Connection provides the following methods to control transactions:

1. setautocommit (Boolean autocommit): sets whether to automatically submit transactions.

2. Commit (): commit a transaction

3. rollback (): cancels a transaction.

The following shows an example of an application:

 
Try {con = Java. SQL. drivermanager. getconnection (dburl, dbuser, dbpwd); // sets the manual commit transaction mode con. setautocommit (false); stmt = con. createstatement (); // database update operation 1 stmt.exe cuteupdate ("update accounts set balance = 900 where id = 1 "); // database update operation 2 stmt.exe cuteupdate ("update accounts set balance = 1000 where id = 2"); con. commit (); // commit transaction} catch (exception e) {try {con. rollback (); // if the operation is unsuccessful, cancel the transaction} catch (exception ex) {// handle an exception ...... } // Handle exceptions ...... } Finally {...}

From the preceding example, we can see that the hibernate transaction boundary is the transaction boundary of the imitator JDBC. In fact, the underlying transaction management of Hibernate is the JDBC transaction management. Let's take a look at the hibernate transaction boundary:

1. Declare the start boundary of the transaction:

Transaction Tx = session. begintransaction ();

2. Submit the transaction: Tx. Commit ();

3. Cancel the transaction: Tx. rollback ();

We are learning JDBCIt is also difficult to learn about Database Transaction Management.JDBCConcurrent transactions. SinceHibernateThe underlying layer is usedJDBCWhen transaction management is implemented, it must also have the problem of multiple transaction concurrency. Let's take a look:HibernateConcurrency of multiple transactions:

• Type 1 lost update: overwrite the updated data committed by other transactions when canceling a transaction.

• Dirty read: one transaction reads the uncommitted update data of another transaction.

• Virtual read: one transaction reads the newly inserted data committed by another transaction.

• Repeatable reading: one transaction reads the updated data committed by another transaction.

• Type 2 lost updates: this is a special case of non-repeated reads. One Transaction overwrites the updated data committed by another transaction.

Here is an example of dirty reading:

The withdrawal transaction changes the deposit balance to 900 yuan at T5 time. The check transfer transaction queries the account's deposit balance at T6 time to 900 yuan. The withdrawal transaction is canceled at T7 time, the check transfer transaction changed the deposit balance to 1000 yuan at the moment of T8. Because the check transfer transaction queries the uncommitted update data of the withdrawal transaction and carries out the update operation based on the query results, if the withdrawal transaction is finally canceled, the bank customer will lose 100 yuan.

Transaction isolation level

For the transaction isolation level, let's look at the two diagrams below the transaction:

It can be seen that the higher the isolation level, the more data integrity and consistency can be ensured, but the greater the impact on concurrency performance. For most applicationsProgramYou can set the isolation level of the database system to read committed, which can avoid dirty reads and has good concurrency performance. Although it may cause non-repeated read, virtual read, and second-type update loss concurrency problems, in some scenarios where such problems may occur, it can be controlled by applications using pessimistic or optimistic locks.

Next, let's take a look at how hibernate configures the isolation level: In the hibernate configuration file, you can explicitly set the isolation level. Each isolation level corresponds to an integer:

1: Read uncommitted

2: Read committed

4: Repeatable read

8: serializable

For exampleCodeSet the isolation level in the hibernate. cfg. xml file to read committed:

Hibernate. Connection. Isolation = 2

For each connection obtained from the database connection pool, Hibernate will change it to the Read committed isolation level.

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.