Hibernate transaction and concurrency problem processing (optimistic lock and pessimistic lock)

Source: Internet
Author: User

I. Definition of database transactions

Second, the database transaction concurrency may bring problems

Third, database transaction isolation LEVEL

Iv. Setting the database isolation level with Hibernate

V. Using pessimistic locks to resolve transaction concurrency problems

Vi. using optimistic locking to resolve transaction concurrency problems

Hibernate transaction and concurrency problem processing (optimistic lock and pessimistic lock)

I. Definition of database transactions

A database transaction, which is a series of operations performed as a single logical unit of work (Transaction). Transaction processing ensures that data-oriented resources are not permanently updated unless all operations within the transactional unit are completed successfully. By combining a set of related actions into a single unit that either succeeds or all fails, you can simplify error recovery and make your application more reliable. To become a transaction, a logical unit of work must satisfy the so-called acid (atomicity, consistency, isolation, and persistence) attributes.

1. atomicity (atomic), the transaction must be an atomic unit of work, either all executed for its data modification, or none of the execution

2. Consistency (consistent), when a transaction is complete, all data must be kept in a consistent state.

3. Isolation (insulation), modifications made by concurrent transactions must be isolated from modifications made by any other concurrent transaction.

4. Persistence (Duration), after the transaction is complete, its effect on the system is permanent.

Second, the database transaction concurrency may bring problems

If there is no lock and multiple users access a database at the same time, problems may occur when their transactions use the same data at the same time. Data inconsistencies due to concurrency include: loss of data modifications, reading of "dirty" data (dirty reads), non-repeatable reads, and phantom data generation:

Suppose the following table is in the database:

1. First class loss update (lost update): In the case of a completely non-isolated transaction, two things update the same data resource, a thing terminates abnormally, rollback causes the first completed update to be lost at the same time.

In the T1 time opened the transaction 1,t2 time to open the transaction 2, in the T3 time transaction 1 from the database to remove the id= "402881e535194b8f0135194b91310001" data, T4 time Transaction 2 took out the same piece of data, T5 Time Transaction 1 update the Age field value to 30,t6 time Transaction 2 Update age to 35 and commit the data, but T7 transaction 1 rolls back the last value of transaction age is still 20, and the update for transaction 2 is lost, which is called "First class lost update (lost Update)".

2. Dirty reads (dirty read): If the second transaction queries to the first transaction that has not yet committed the update data, it forms a dirty read.

In the T1 time opened the transaction 1,t2 time opened Transaction 2, in T3 time transaction 1 from the database to remove the id= "402881e535194b8f0135194b91310001" data, at T5 time transaction 1 to update the value of age to 30, but the transaction has not yet committed, T6 time Transaction 2 reads the same record, obtains the value of age is 30, but transaction 1 has not yet committed, if the T7 time transaction 1 ROLLBACK TRANSACTION 2 data is the wrong data (dirty data), this situation is called "dirty Read (Dirty Read)".

3. Virtual read (Phantom Read): A transaction to execute two queries, the second result set contains the first time no or some rows have been deleted, resulting in two inconsistent results, but another transaction in the middle of the two queries inserted or deleted data caused.

At the moment of T1 the transaction is opened 1,t2 the transaction is 2,T3 at the moment transaction 1 queries all records from the database, records have a total of one, T4 time transaction 2 inserts a record into the database, T6 time transaction 2 commits the transaction. T7 Transaction 1 when querying data data again, the record becomes two. This situation is "virtual read (Phantom Read)".

4. Non-repeatable read (unrepeated Read): A transaction two reads the same row of data, the result is different status results, such as in the middle just another transaction updated the data, two times the results are not the same, not trusted.

In the T1 time opened the transaction 1,t2 time to open the transaction 2, in T3 time transaction 1 from the database to remove the id= "402881e535194b8f0135194b91310001" data, at this time Age=20,t4 time Transaction 2 Query the same piece of data, T5 Transaction 2 Update data AGE=30,T6 Transaction 2 commits a transaction, T7 transaction 1 queries the same data, discovers that the data is inconsistent with the first time. This is the case of "non-repeatable read (unrepeated read)".

5. The second category of lost updates (second lost updates): is a special case of non-repeatable read, if two transactions are read the same line, and then two are written, and submitted, the first transaction changes will be lost.

The transaction is opened at T1 time 1,t2 time transaction 1 Update data AGE=25,T5 time Transaction 2 Update data AGE=30,T6 time to commit the transaction, T7 time Transaction 2 commits the transaction, the update of transaction 1 is overwritten. This is the second category of missing updates (second lost updates).

Third, database transaction isolation LEVEL

In order to solve the various problems of database transaction Concurrency Runtime, the database system provides four levels of transaction isolation:
1. Serializable serialization
2. REPEATABLE Read REPEATABLE reading
3. Read commited readable submitted
4. Read Uncommited Non-committed

The relationship between the isolation level and concurrency performance:

The issues that each isolation level can address:

Iv. Setting the database isolation level with Hibernate

The configuration database transaction isolation level that can be displayed in Hibernate's configuration file. Each isolation level is represented by an integer:

8-serializable serialization
4-repeatable Read Repeatable reads
2-read commited Readable submitted
1-read uncommited Readable uncommitted

Use the Hibernate.connection.isolation parameter in Hibernate.cfg.xml to configure the database transaction isolation level.

V. Using pessimistic locks to resolve transaction concurrency problems

Pessimistic locking, as its name implies, is a conservative attitude to the data being modified by the outside world (including other transactions currently in the system, as well as transactions from external systems), so that the data is locked during the entire data processing process. Pessimistic lock implementation, often rely on the database provided by the lock mechanism (also only the database layer provides a lock mechanism to truly guarantee the exclusivity of data access, otherwise, even in this system to implement the locking mechanism, there is no guarantee that the external system will not modify the data).

A typical pessimistic lock call that relies on a database: SELECT * from account where name= ' Erica ' for update this SQL statement locks all records that meet the search criteria (name= "Erica") in the list. These records cannot be modified by the outside world before the transaction commits (the locks in the transaction are freed during transaction commits). Pessimistic lock is also a database-based lock mechanism implementation.

Pessimistic locking is easy to use in hibernate, but pessimistic locking is rarely used in real-world applications because it restricts concurrency significantly:

Figure for the Get method of the Hibernate3.6 Help document session document, you can see the Get method the third parameter "Lockmode" or "lockoptions", notice in Hibernate3.6 above version "Lockmode" It is not recommended. The third parameter of the method is to set the pessimistic lock, and after using the third argument, each of the SQL statements we send will be followed by a "for update" to tell the database to lock the relevant data.

Lockmode parameter Select this option to turn on pessimistic locking.

T1,T2 time withdrawal transaction and transfer transactions opened, T3 Transaction query accounts table data and pessimistic lock lock, T4 Transfer Transaction also query the same data, the database found that the record has been used by the previous transaction using pessimistic lock lock, and then let the transfer transaction wait until the withdrawal transaction submitted. T6 Time Withdrawal transaction submission, T7 time transfer transactions to obtain data.

Vi. using optimistic locking to resolve transaction concurrency problems

Relative pessimistic lock, the optimistic locking mechanism adopts a more relaxed locking mechanism. Pessimistic locking relies on the lock mechanism of the database in most cases, to ensure the maximum degree of exclusivity of the operation. But it comes with a lot of overhead for database performance, especially for long transactions, which are often unsustainable. The optimistic locking mechanism solves this problem to some extent. Optimistic locking, mostly based on the data version (versions) recording mechanism implementation. What is a data version? is to add a version identity to the data, which is typically done by adding a "version" field to the database table in the version solution based on the database table.
How optimistic locks work: When you read out the data, read the version number together, and then update it, add one to the version number. At this point, the version data of the submitted data is compared to the current version information of the database table corresponding to the record, and if the submitted version number is greater than the current version number of the database table, it is updated, otherwise it is considered to be outdated data.

Hibernate provides 3 implementations for optimistic locking:

1. Based on version

2. Based on timestamp

3. Add optimistic lock for legacy items

To configure a version-based optimistic lock:

<?xml version= "1.0" encoding= "Utf-8"?>
<! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

<class name= "Com.suxiaolei.hibernate.pojos.People" table= "People" >
<id name= "id" type= "string" >
<column name= "id" ></column>
<generator class= "UUID" ></generator>
</id>

The <!--version label specifies the field information that represents the version number--
<version name= "Version" column= "version" Type= "integer" ></version>

<property name= "name" column= "name" type= "string" ></property>

</class>

To configure an optimistic lock based on timestamp:

<?xml version= "1.0" encoding= "Utf-8"?>
<! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

<class name= "Com.suxiaolei.hibernate.pojos.People" table= "People" >
<id name= "id" type= "string" >
<column name= "id" ></column>
<generator class= "UUID" ></generator>
</id>

<!--timestamp label specifies the field information that represents the version number--
<timestamp name= "Updatedate" column= "Updatedate" ></timestamp>

<property name= "name" column= "name" type= "string" ></property>

</class>

Legacy Project, for various reasons cannot add "version" or "Timestamp" field for the original database, this time can not use the above two ways to configure optimistic lock, hibernate for this situation provides a "Optimisitic-lock" property, which is located in <class> on the label:

<?xml version= "1.0" encoding= "Utf-8"?>
<! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">

<class name= "Com.suxiaolei.hibernate.pojos.People" table= "People" optimistic-lock= "all" >
<id name= "id" type= "string" >
<column name= "id" ></column>
<generator class= "UUID" ></generator>
</id>

<property name= "name" column= "name" type= "string" ></property>
</class>

Set the value of this property to all so that all fields of the record are version control information.

Hibernate transaction and concurrency problem processing (optimistic lock and pessimistic lock)

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.