执行mysql update 的时候,会对数据库表 加锁;
使用 update * set where 条件的时候 ,innodb 会默认行级锁,如果不带id 会升级为表锁
继续--
执行update 并使用id作为条件, 再commit之前,数据库行级 锁定;此时别人无法修改这条数据;
模拟场景:
------------------------ 用户1-------------
{
this.update1();
sleep(2s);
commit;
}
------------------------ 用户2-------------
{
this.update2();
commit;
}
-- 用户1 执行update1, 事务没有提交, 这时用户2执行update2,不会被执行,mysql会处于等待状态;
只有用户1 commit以后,用户2 才会继续执行update2
-- 加入version 以后 假定原版本号 为0
用户1 ,用户2 并发; 查询版本号都是0;
用户1 update 以后变为1 ;用户2 在用户1 commit以后才会执行update ;
此时 update set version = version + 1 where id= 1 and version = #{version}
此时 update set version = version + 1 where id= 1 and version = 0; (version实际已经等于1)
执行更新影响行数 为0; 根据结果 <1 认定用户2的数据已经被更改,处理失败