简体   繁体   中英

Issue in Pagination Spring data

I am trying to implement pagination in Services. Using Cassandra as a database My code works fine if query returns some small number of list. I am just filtering out with number off pages[hardcoded as 100/ dont want to hardcode rather to return as param] and offset value. So for every request i dont want to make a query. Am sure there should be a possible way to set offset value in query itself. My code-

  @RequestMapping(value = "/find/customerreqbyperiod", method = RequestMethod.GET,
  produces = "application/json")
  @ResponseBody
  public List<CustomerReq> findCustomerRequest(@RequestParam(value = "productid") final String pProductId,
  @RequestParam(value = "dataperiod") final String pdataPeriod,
  @RequestParam(value = "offset") final int offset)
  {
   List<CustomerReq> requestList = null;

   try
   {
    requestList = requestService.findCustomerRequest(pProductId, pdataPeriod, offset);
      if (requestList == null || offset > requestList.size()) return new ArrayList<CustomerRequestV2>();

       int numberOfItems = 10;
       int fromIndex = offset;
       int toIndex = Math.min(offset + numberOfItems, requestList.size());

        return requestList.subList(fromIndex, toIndex);
       }
  catch (final ServiceException e)
    {
     LOG.error(ERROR_RETRIEVING_LIST + pProductId, e);
    }
   return requestList;
  }

@Repository-

   @Query("select * from customer_request where product_id = ?0 and data_period = ?1")
   List<CustomerReq> findByProductIdAnddataPeriod(String productId, String dataPeriod, int offset);

Please provide your valuable Suggestion. Thank you!-Saurav

I think you should you use Pageable here for example:

public interface ProductRepository extends JpaRepository<Product, Long> {
    @Query("select cr from customer_request cr where cr.product_id = :productId and cr.data_period = :dataPeriod")
    Page<CustomerReq> findByProductIdAnddataPeriod(@Param("productId") String productId, @Param("dataPeriod") String dataPeriod, Pageable pageable);
}

And pass PageRequest with offset:

PageRequest pageRequest = new PageRequest(pageNumber, offset);
Page<CustomerReq> customerReqsPage = findByProductIdAnddataPeriod("productId","datePeriod", pageRequest);
List<CustomerReq> customerReqs = customerReqsPage.getContent();

UDP : Unfortunately it's not supported for Cassandra. JIRA ticket for that: jira.spring.io/browse/DATACASS-56

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM