问题一:
当事务隔离级别设置为可重复读的时候,将所有select过的行都加了读锁,并且记录了版本号,当update 的时候们如果发现版本号变了,则事务失败回滚。不知道我这样理解是否正确?
问题二:
如果上面的理解正确,那是否innodb的可重复读这个隔离级别已经帮我们实现了乐观锁,所以并不需要手动通过版本或者时间戳来实现乐观锁,或者使用 悲观锁了?
问题三:
悲观锁 select ... for update 是增加了一个写锁? 所以所有的读写都会被block住?
问题四:
假设有事务A,先select 然后 update,事务B同样也是先select 然后再update
如果事务隔离级别为可重复读,事务A,B先后select加上了读锁,那么会不会因此而后面的update操作会互相block住,导致死锁?
问题一和问题四好像是矛盾的,因为如果问题四成立,事务会block住,也不会修改成功导致版本号不一致导致 回滚了。
Question 1:
During repeatable reading (REPEATABLE READ), ordinary SELECT does not add a read lock (does innodb have the concept of read lock?), but mysql caches the SELECT result set to ensure that the same is true in this transaction. The results obtained by the SELECT statement are always consistent. Therefore, there is no problem of incorrect version number during UPDATE, and there will be no rollback.
You can refer to: http://dev.mysql.com/doc/refman/5.6/en/innodb-consistent-read.html
Question 2:
For repeatable read-level transactions, because you are in the transaction, as long as you do not COMMIT, no modification will occur, and you cannot read the data updated by others, so you can neither add optimistic locking nor judge before COMMIT. Whether others have updated the data, this makes it impossible for you to implement optimistic locking anyway.
Only using READ COMMITTED can you achieve the optimistic locking you want.
Question 3:
FOR UPDATE locks all selected records. It is a write lock. All writes will be blocked. Ordinary SELECT will not be blocked.
Question 4:
Because there is no so-called read lock, the problem you think does not exist.
This problem is a bit complicated. According to the definition of transaction isolation, repeatable reading requires a read lock:
Wiki Chinese description
Wiki English description
That is to ensure that the read content will not change.
But according to the mysql documentation, the implementation mechanism of innodb is to create a snapshot when reading to ensure that the read content does not change within a single transaction: mysql documentation
Then there are some subtle differences. . . Although there is no difference in the results=. =
Questions 1 and 2 are as @Huan Du said, there is no read lock so it will not fail. You need to implement the lock yourself
Question 4: There will be no deadlock