준준의 기록일지

[Spring] Paging 처리 코드 본문

스프링

[Spring] Paging 처리 코드

junjunwon 2021. 12. 14. 13:39

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."




Controller 

@RequestMapping(value="/getLogPage")
  public ResponseEntity<Page<AccessLog>> getLogPage(
      @RequestParam("hostIp") String hostIp
      ,@RequestParam("vmId") String vmId
      , @RequestParam("range") Integer range
      , @RequestParam("page") Integer page) {
    
    Page<AccessLog> acsLog = apiService.getLogPage(hostIp, vmId, range, (page-1<0)?0:page-1);
    
    return new ResponseEntity<Page<AccessLog>>(acsLog, HttpStatus.OK);
  }

===========================================================================================================  

Service  public Page<AccessLog> getLogPage(String hostIp, String vmId, int range, int page) {
    int size = range;
    PageRequest pageRequest = PageRequest.of(page, size, Sort.by("connectTime").descending());
    
    if( (hostIp != null && !hostIp.isEmpty()) && (vmId != null && !vmId.isEmpty()) )
      return accessLogRepository.findByHostIpAndVmId(hostIp, vmId, pageRequest);
    else if( (hostIp != null && !hostIp.isEmpty()) )
      return accessLogRepository.findByHostIp(hostIp, pageRequest);
    else if( (vmId != null && !vmId.isEmpty()) )
      return accessLogRepository.findByVmId(vmId, pageRequest);
    else
      return accessLogRepository.findAll(pageRequest);
    
  }
  
===========================================================================================================
  Repository

  public Page<AccessLog> findByHostIpAndVmId(String hostIp, String vmId, Pageable  pageable);
  
  public Page<AccessLog> findByHostIp(String hostIp, Pageable  pageable);
  
  public Page<AccessLog> findByVmId(String vmId, Pageable  pageable);