Mysql insert into...select...no lock problem

业务需求:一个人一天只能有一次签到,多客户端同时点击签到,

异常场景:虽然代码里面有判断是否重复签到的逻辑,但是在极短的时间内,在多个客户端签到,可能会出现多次签到成功

技术背景:mysql、mybatis

实现思路:插入前查询一下表里面是否存在 userId 和 signDate 的数据,如果存在则不插入。

具体实现:
    insert into sign_201804(<include refid = "BaseColumn"/>) 
    select #{id},#{userId},#{signDate},#{bonus},#{lat},#{lng}... FROM DUAL
        where NOT EXISTS ( select userId from sign_201804
                                    where userId = #{userId} and signDate = #{signDate} )
    <selectKey keyProperty= "id" resultType= "Long" order= "AFTER">
         SELECT LAST_INSERT_ID()
    </selectKey>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325261441&siteId=291194637