Handle Hibernate transactions and concurrency issues

Source: Internet
Author: User

I. Definition of database transactions

Database Transaction refers to a series of operations performed as a single logical unit of work. Transaction Processing ensures that data-oriented resources are not updated permanently unless all operations in the transaction unit are successfully completed. By combining a set of related operations into a unit that either succeeds or fails, you can simplify error recovery and make the application more reliable. To become a transaction, a logical unit of work must meet the so-called ACID (atomicity, consistency, isolation, and durability) attributes.

1. atomicity (atomic): A transaction must be an atomic unit of work. modifications to its data must either be executed in all or not.

2. consistent. When a transaction is completed, all data must be consistent.

3. Isolation (insulation). modifications made by a concurrent firm must be isolated from those made by any other concurrent firm.

4. Duration: after a transaction is completed, its impact on the system is permanent.

Ii. Problems arising from Database Transaction concurrency

If it is not locked 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 inconsistency caused by concurrent operations includes: data loss and modification, dirty Data Reading, non-repeated data reading, and ghost data generation:

Assume that the database has the following table:

1. the first type of lost update: When two transactions are completely isolated, the same data resource is updated, and a transaction ends abnormally, rollback results in the loss of the first update.

Transaction 1 is enabled at T1, transaction 2 is enabled at T2, and transaction 1 extracts data with id = "402881e535194b8f0135194b91310001" from the database at T3, transaction 2 at T4 extracts the same data, transaction 1 at T5 time updates the value of the age field to 30, and transaction 2 at T6 time updates the value of the age field to 35 and submits the data, however, if T7 transaction 1 rolls back the transaction age, the last value is still 20, and the update of transaction 2 is lost, this is called "the first type of lost update )".

2. dirty read: If the second transaction queries the updated data not committed by the first transaction, dirty read is formed.

Transaction 1 is enabled at T1, transaction 2 is enabled at T2, and transaction 1 extracts data with id = "402881e535194b8f0135194b91310001" from the database at T3, at the T5 moment, transaction 1 updated the value of age to 30, but the transaction was not committed. At the T6 moment, transaction 2 read the same record and obtained the value of age to 30, but transaction 1 was not committed, if transaction 1 rolls back the data of transaction 2 at the time of T7, it is the wrong data (dirty data), which is called "dirty read )".

3. phantom read: A transaction executes two queries. The second result set contains no or some rows that have been deleted for the first time, resulting in inconsistent results, this is only because another transaction inserts or deletes data in the middle of the two queries.

Transaction 1 is enabled at T1. transaction 2 is started at T2. transaction 1 is queried from the database at T2. A total of one record exists, t4 moment transaction 2 inserts a record into the database, T6 moment transaction 2 commits the transaction. When T7 transaction 1 queries data again, the record is changed to two. This is "phantom read )".

4. unrepeated read: A transaction reads data from the same row twice and returns results in different States. For example, if another transaction updates the data, the results are different, untrusted.

Transaction 1 is enabled at T1 and transaction 2 is enabled at T2. At T3, transaction 1 extracts data with id = "402881e535194b8f0135194b91310001" from the database. At this time, age = 20, t4 moment transaction 2 queries the same data, T5 transaction 2 updates data age = 30, T6 moment transaction 2 commits the transaction, T7 transaction 1 queries the same data, and finds that the data is inconsistent with the first time. This is "unrepeated read )".

5. second lost updates: this is a special case where duplicate reads are not allowed. If both transactions read the same row, then both transactions write and commit, changes made by the first firm will be lost.

Transaction 1 is enabled at T1. transaction 2 is started at T2. transaction 1 is updated at T3. transaction 2 is updated at T3. transaction 2 is updated at T3. transaction 1 is committed at T4, t7 moment transaction 2 commits the transaction and overwrites the update of transaction 1. This is the second type of Missing Update (second lost updates )".

Iii. database transaction isolation level

The database system provides four transaction isolation levels to solve various problems during concurrent database transactions:

1. Serializable

2. Repeatable Read

3. Read Commited Read committed

4. Read Uncommited Read not submitted

Relationship between isolation level and concurrency performance:

Problems that can be solved at each isolation level:


 

Iv. Use Hibernate to set the database isolation level

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

8-Serializable

4-Repeatable Read

2-Read Commited Read committed

1-Read Uncommited Read not submitted

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

5. Use pessimistic locks to solve transaction concurrency Problems

Pessimistic lock, as it is called, refers to a conservative attitude towards data being modified by external systems including the current transactions of the system and the transactions from the external system, the data is locked during the entire data processing process. The implementation of pessimistic locks often relies on the locks mechanism provided by the database and the locks mechanism provided by the database layer to ensure data access exclusive. Otherwise, even if the lock mechanism is implemented in the system, it cannot guarantee that the external system will not modify the data ).

A typical pessimistic lock call depending on the database: select * from account where name = "Erica" for update this SQL statement locks all entries in the account table that meet the search criteria name = "Erica "). The locks in the transaction process will be released when the transaction is committed before the transaction is committed. These records cannot be modified. Pessimistic locks are also implemented based on database locks.

It is very easy to use pessimistic locks in Hibernate, but pessimistic locks are rarely used in actual applications, because they greatly limit concurrency:

The figure shows the get method in the Session document of the Hibernate3.6 help document. The third parameter of the get method is "lockMode" or "lockOptions ", note that "LockMode" is not recommended in Hibernate3.6 or later versions. The third parameter of the method is used to set the pessimistic lock. After the third parameter is used, "for update" will be added to each SQL statement sent to tell the database to lock related data.

If this option is selected for the LockMode parameter, the pessimistic lock is enabled.

The withdrawal transaction and transfer transaction are enabled at T1 and T2 respectively. The T3 transaction queries the data in the ACCOUNTS table and locks it with a pessimistic lock. The T4 transfer transaction also needs to query the same data, the database finds that the record has been locked by the pessimistic lock of the previous transaction, and then let the transfer transaction wait until the withdrawal transaction is committed. The withdrawal transaction is committed at T6, And the transfer transaction obtains data at T7.

6. Use optimistic locks to solve transaction concurrency Problems

Compared with pessimistic locks, optimistic locks adopt a more loose locking mechanism. Pessimistic locks are implemented by the database lock mechanism in most cases to ensure maximum operation exclusiveness. However, there is a large amount of database performance overhead, especially for long transactions, which is often unbearable. The Optimistic Locking Mechanism solves this problem to some extent. Optimistic locks are mostly implemented based on the data Version) record mechanism. What is the data version? Add a version ID for the data. In the database table-based version solution, you can add a "version" field to the database table.

How optimistic locks work: Read the data, read the version number together, and add a new version number when updating the data. In this case, the version data of the submitted data is compared with the current version information recorded in the database table. If the submitted data version number is greater than the current version number of the database table, it is updated, otherwise, expired data is considered.

Hibernate provides three implementations for optimistic locks:

1. version-based

2. Based on timestamp

3. Add optimistic locks to legacy projects

Configure the version-based Optimistic lock:

 
  1. <? Xml version = "1.0" encoding = "UTF-8"?>
  2. <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate Mapping DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  3.  
  4. <Hibernate-mapping>
  5. <Class name = "com. suxiaolei. hibernate. pojos. People" table = "people">
  6. <Id name = "id" type = "string">
  7. <Column name = "id"> </column>
  8. <Generator class = "uuid"> </generator>
  9. </Id>
  10. <! -- Version label is used to specify the field information indicating the version number -->
  11. <Version name = "version" column = "version" type = "integer"> </version>
  12.  
  13. <Property name = "name" column = "name" type = "string"> </property>
  14. </Class>
  15. </Hibernate-mapping>

Configure the optimistic Lock Based on timestamp:

 
  1. <? Xml version = "1.0" encoding = "UTF-8"?>
  2. <! DOCTYPE hibernate-mapping PUBLIC "-// Hibernate/Hibernate Mapping DTD 3.0 // EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  3.  
  4. <Hibernate-mapping>
  5. <Class name = "com. suxiaolei. hibernate. pojos. People" table = "people">
  6. <Id name = "id" type = "string">
  7. <Column name = "id"> </column>
  8. <Generator class = "uuid"> </generator>
  9. </Id>
  10. <! -- Timestamp label is used to specify the field information indicating the version number -->
  11. <Timestamp name = "updateDate" column = "updateDate"> </timestamp>
  12.  
  13. <Property name = "name" column = "name" type = "string"> </property>
  14. </Class>
  15. </Hibernate-mapping>

For legacy projects, the "version" or "timestamp" field cannot be added to the original database for various reasons. In this case, you cannot use the above two methods to configure optimistic locks, hibernate provides an "optimisitic-lock" attribute for this situation, which is located on the <class> label:

 
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
  3.  
  4.     <class name="com.suxiaolei.hibernate.pojos.People" table="people" optimistic-lock="all"> 
  5.         <id name="id" type="string"> 
  6.             <column name="id"></column> 
  7.             <generator class="uuid"></generator> 
  8.         </id> 
  9.  
  10.         <property name="name" column="name" type="string"></property> 
  11.     </class> 

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

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.