代码改造实录--分页查询先限定条件再查询,而非查询后再加条件判断

 

原来的代码:

        Outpatient outpatientQuery = new Outpatient();
        outpatientQuery.setUserId(user.getId());
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, 8, sort);
        Page<Outpatient> pages = outpatientService.queryOutpatients(outpatientQuery, pageable);

        List<InformationVo> informationVoVoList = new ArrayList<>();
        for (Outpatient out : pages.getContent()) {
            Long createTime = out.getCreateTime();

            Long dayTime = Long.valueOf(System.currentTimeMillis());

            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(createTime);
            calendar.add(Calendar.DATE, 20);
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTimeInMillis(createTime);
            calendar1.add(Calendar.DATE, 23);
            long beginTime = calendar.getTimeInMillis();
            long endTime = calendar1.getTimeInMillis();

            if (dayTime.compareTo(beginTime) >= 0 && dayTime.compareTo(endTime) <= 0) {
           ......
            }
        }

修改后代码:

        Calendar calendarStart = Calendar.getInstance();
        calendarStart.add(Calendar.DATE, -23);
        Calendar calendarEnd = Calendar.getInstance();
        calendarEnd.add(Calendar.DATE, -20);

        OutpatientQuery outpatientQuery = new OutpatientQuery();
        outpatientQuery.setUserId(userId);
        outpatientQuery.setCreateTimeStart(calendarStart.getTimeInMillis());
        outpatientQuery.setCreateTimeEnd(calendarEnd.getTimeInMillis());
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page, 8, sort);
        Page<Outpatient> pages = outpatientService.queryOutpatients(outpatientQuery, pageable);

        List<InformationVo> informationVoVoList = new ArrayList<>();
        for (Outpatient out : pages.getContent()) {
           ......
        }

修改后:

  1、代码减少,逻辑更清楚;

  2、减少无效的数据访问;

  3、修正了分页信息。

posted @ 2020-07-27 16:55  GreenMountain  阅读(284)  评论(1编辑  收藏  举报