Mybatis version乐观锁实现并发控制


   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 } )



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}


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;
}
}


你可能感兴趣的:(数据库并发控制)