記錄一次遞迴查詢的運用

dead_lee發表於2021-09-09

背景:多個人隨機拉取一條公共池裡面乾淨的資料,保證可以將池子裡所有資料處理完,並且已經處理完的資料不可被覆蓋
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,表設計
圖片描述

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4686/viewspace-2822289/,如需轉載,請註明出處,否則將追究法律責任。

相關文章