ITPub博客

首页 > IT职业 > IT图书 > 记录一次递归查询的运用

记录一次递归查询的运用

IT图书 作者:dead_lee 时间:2021-09-09 10:27:56 0 删除 编辑

背景:多个人随机拉取一条公共池里面干净的数据,保证可以将池子里所有数据处理完,并且已经处理完的数据不可被覆盖
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博客 ” ,链接:https://blog.itpub.net/4686/viewspace-2822289/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2021-06-25

  • 博文量
    82
  • 访问量
    15435