Mybatis version乐观锁实现并发控制

本文介绍了如何使用Mybatis的version字段实现乐观锁,防止重复插入并进行并发更新操作。通过尝试插入,若失败则查询当前版本号,多次尝试更新直至成功或达到重试上限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<insert id="insertNotExists" >
   insert into tf_app_call_count (id,api_key, 
     api_secret, api_id,
     create_time, update_time, create_user, 
     update_user, valid)   SELECT 
  #{id,jdbcType=BIGINT}, #{apiKey,jdbcType=VARCHAR}, 
     #{apiSecret,jdbcType=VARCHAR}, #{apiId,jdbcType=VARCHAR},
     #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}, #{createUser,jdbcType=BIGINT}, 
     #{updateUser,jdbcType=BIGINT}, #{valid,jdbcType=BIT} 
     from dual where not exists(select id from tf_app_call_count where api_key = #{apiKey} and valid =1 and
     api_secret = #{apiSecret } and api_id = #{apiId } )
</insert>
<select id="selectByKeyAndApiId" resultType="long">
select version from  tf_app_call_count   where api_key = #{apiKey} and valid =1 and
     api_secret = #{apiSecret } and api_id = #{apiId }  limit 1 --
</select>
<update id="updateByVersion" parameterType="com.niwodai.indonesia.entity.AppCallCount">
update tf_app_call_count set  version=version+1 ,num= num+1 where  api_key = #{apiKey} and valid =1 and
     api_secret = #{apiSecret } and api_id = #{apiId }  and version=#{version}

</update>


1)避免重复插入

2)存在了就更新

                       

int insertCount = appCallCountMapper.insertNotExists(appCallCount);
if (insertCount==0) {
Long version = appCallCountMapper.selectByKeyAndApiId(apiKey,apiSecret,apiId);
int call = 0;
appCallCount.setVersion(version);
while (appCallCountMapper.updateByVersion(appCallCount)==0) {
if (call++==3) 
break;
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值