乐观锁:
简单的来说:就是认为别人不会过来修改它的数据,常见的乐观锁通常会带一个version(版本),等到提交的时候,会去检查一下版本,如果版本修改了,就会抛出异常,并且回滚数据;
乐观锁通常需要在表中额外设计一个version的冗余字段
并且在插入数据的时候,将version初始化为0
常见的乐观锁如下,注意version
<update id="updateBasicInfo">
update `user_info`
set version = version + 1,
bit_state = #{bitState},
phone_number = #{phoneNumber},
real_auth_id = #{realAuthId},
marriage_id = #{marriage.id},
kid_count_id = #{kidCount.id},
education_background_id = #{educationBackground.id},
house_condition_id = #{houseCondition.id},
income_grade_id = #{incomeGrade.id}
where id = #{id} and version = #{version}
</update>
在Service层,一但修改失败,就可以抛出异常了,通常是“服务器忙,请稍后再试”
悲观锁:
简单的来说就是:认为谁都会过来修改它的数据,所以无论在做什么操作的时候,都会加把锁,等自己操作完成之后,才会将锁放开
与乐观锁依靠程序员自己实现不同的是,悲观锁是依靠数据库自带的锁机制实现的
数据库中(仅仅以MySQL为例)常见的锁有
-
表锁
-
共享锁
-
行锁
表锁很简单:
扫描二维码关注公众号,回复: 4247126 查看本文章
begin;
select * from ip_log for update
这个表锁很简单,在Navicat中再启动个命令界面,发现无论是update或者是insert都处于等待状态
除非commit不然无法进行下一步操作
共享锁:
begin;
select * from user where id = 1 lock in share mode;
共享锁没什么好说的,但是需要注意的是:
update,insert操作是不能加共享锁的,因为update,insert,delete自带排他锁,加了会报语法错误
mysql> update user set name = 'kiki' where id = 7 lock in share mode;
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'lock in share mode' at line 1
行锁
begin;
select * from user where id = 1 lock in share mode;*
这样就能给id = 1加上行锁了