mysql update of data loss solution

The latest look at "innodb engine insider", the author introduces a problem of lost updates, here to record their ideas and programs

-------------------------------------------------------------------

Problem Description:

 lost update mysql database definition :( actually lost updates without problems in the database point of view, the source of the application logic issues update problems)

  1 1. The transaction data in a local cache query row, and displayed to the user user1 -> select balance from account where user = 'a';

  2. 2 query transaction data on the same line of the local cache, and display to the user user2 -> select balance from account where user = 'a';

  3. user1 to modify this data, and submit the updated database -> update account set balance = balance -100 where user = 'a';

  4. user2 user to modify the displayed data, and submit the updated database -> update account set balance = balance -800 where user = 'a';

   Obviously the above user1 updated data loss, and this is updated to cover, such as the user transfers operation. a total of 1000 accounts, transaction 1 and transaction 2 check account is 1000, then the transaction account deductions 1 100 submitted. Services 2 800 deduction submit. This time account balance of 200, 100 will be deducted 1 transaction was missing, which can lead to serious problems.

-------------------------------------------------------------------

Being thought of two solutions:

Solution 1: Use the pessimistic locking

  1)使用顺序 --> select balance from account where user= 'a'  for update 

  2)更新 --> update account set balance = balance -100 where user= 'a'     

Solution 2: Use optimistic locking

  1) increase the field jpa_version int table version number -> select balance, version from account where user = 'a'  

  2) 更新 --> update account set balance = balance -100 where user= 'a' and jpa_version = ${version}             

to sum up:

  For direct use pessimistic account trading advice, high performance database, there is not much difference in the degree of concurrency is not very high performance both scenes. If the transaction is reduced inventory operation can be considered optimistic locking to ensure concurrency.

 

Guess you like

Origin www.cnblogs.com/immer/p/10930020.html