Search code examples
springspring-bootspring-mvcpaginationhibernate-query

Pagination in Spring using @RestController, but without using Spring Data Rest Pageable?


I know using Spring Data Rest I can use the in-built functionality of Pagination Like this

Page<Product> findByCategoryId(@RequestParam("id") Long id, Pageable pageable);

However, I am in project I am using Spring mvc @RestController and want to achive the same functionality I tried like this:-

Session currentSession = entityManager.unwrap(Session.class);
Query<Product> theQuery = currentSession.createQuery("from Product", Product.class);
theQuery.setFirstResult((pageNumber-1) * pageSize); // This is 0 based
theQuery.setMaxResults(pageSize);
List<Product> dataList = theQuery.getResultList();  
return dataList;

It works but I don't get the count of total number of records in the table. And for UI pagination I need that.

So do I have to hit 2 queries everytime first like above then 1 query to fetch record size. (Which can cause data sync problems if records are updated)

Or

Is there a better way to achieve this in SINGLE QUERY


Solution

  • If you need the total number of records then you must create a second query.

    You could do that in one query with a subquery but then you cannot use Entities as return type.

    Regarding data sync problems: If you run both queries in the same transaction there is no problem.

    Btw. why do you unwrap the Hiberante Session? There is no need for that in your example.