Pessimistic locks, optimistic locks, row-level locks, table-level locks

The update is lost: the newly changed coverage is changed first, and there are three ways to solve it in the development

1. Raise the transaction level to the highest level TRANSACTION_SERIALIZABLE

Both sides of the operation must upgrade the level; the query uses the shared lock; the update uses the update lock; one query and the other update, the shared lock and the update lock will conflict; when the two sides update the lock and a deadlock occurs, the program will automatically roll back the operation of one party to avoid update lost

2. Pessimistic locks (table-level locks are added)

One side: query statement plus  for update; the other side: query statement plus  for update; when the update statement is performed, the other side cannot perform the update operation

3. Optimistic locking

The update statement sets the version number and updates the data in the specified version

一方:update account set money=money-200,version=version+1 where id=1 and version=0;

If the other party operates the same version number, the data cannot be updated

另一方:update account set money=money+200,version=version+1 where id=1 and version=0;

If there are many updates and few queries, use pessimistic locking; otherwise, optimistic locking

Table-level lock, where uses a non-primary key

Row-level lock, where the primary key is usually id

If table-level locks are used, other clients will not be able to perform query operations, so remember to use row-level locks during development

Taking mysql as an example, when there is an index and the index is used, it is a row lock , and when there is no index, it is a table lock . Innodb  's row lock is in the case of an index , and a table without an index locks the entire table .

Row-level locks generally refer to exclusive locks , that is, locked rows cannot be modified or deleted, but can only be selected by other sessions. Before row-level locks, table structure shared locks need to be added .

Table-level locks generally refer to table structure shared locks . DDL operations cannot be performed on the table , but there are no restrictions on DML operations.
Before row-level locks, table structure shared locks need to be added .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326353131&siteId=291194637