手记

记录一次递归查询的运用

背景:多个人随机拉取一条公共池里面干净的数据,保证可以将池子里所有数据处理完,并且已经处理完的数据不可被覆盖
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,表设计

1人推荐
随时随地看视频
慕课网APP