继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

记录一次递归查询的运用

judyW
关注TA
已关注
手记 47
粉丝 11
获赞 107

背景:多个人随机拉取一条公共池里面干净的数据,保证可以将池子里所有数据处理完,并且已经处理完的数据不可被覆盖
1,Service

 @Override
    @Transactional(rollbackFor = Exception.class)
    public MarkTextPO pullMarkText(Long userId) {
        MarkTextPO markTextPO;
        //先将属于自己但未完成的数据取出
        markTextPO = markTextPOMapper.selectUnFinishedByUserId(userId);
        //从公海中取,并打上标记
        if (markTextPO == null) {
            markTextPO = getFromPublic(userId);
        }
        return markTextPO;
    }

    private MarkTextPO getFromPublic(Long userId) {
        int max = 10000;
        MarkTextPO markTextPO = getRandomPO(max);
        if (Objects.isNull(markTextPO)) {
            return null;
        }
        Long flag = markTextPOMapper.updateByOwnerUserId(markTextPO.getMarkTextId(), userId);
        if (flag < 1) {
            return getFromPublic(userId);
        }
        return markTextPO;
    }

    private MarkTextPO getRandomPO(int max) {
        if (max < 1) {
            return null;
        }
        int next = random.nextInt(max);
        MarkTextPO markTextPO = markTextPOMapper.selectUnFinished(next);
        if (Objects.isNull(markTextPO)) {
            return getRandomPO((next + 1) / 2);
        }
        return markTextPO;
    }

2,mapper

   <select id="selectUnFinishedByUserId" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from mark_text
        <where>
            finish_status = 2
            and own_user_id = #{userId}
            and enabled_status = 1
        </where>
        limit 1
    </select>


    <select id="selectUnFinished" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from mark_text
        <where>
            finish_status = 2
            and own_user_id = 0
            and enabled_status = 1
        </where>
        limit #{next},1
    </select>
    
  <update id="updateByOwnerUserId">
        update mark_text
        set own_user_id = #{userId}
        where mark_text_id = #{markTextId}
        and own_user_id = 0
    </update>

3,表设计
图片描述

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP