0

What I'm curious about is whether the paging processing logic should be written in the service layer or the controller layer.

Here, the paging process logic is the task of getting the totalCount from the database and getting the total number of pages through pageSize(offset).

I think the paging process is related to the view, I thought it could be handled in the controller.

Ted Vu
  • 29
  • 1
  • 5
changuk
  • 151
  • 4

2 Answers2

1

Usually when using pagination you receive the parameters from the client (e.g. page size, pages to retrieve). Which means you would need to receive and handle those data via the controller. In order to get only the requested data you forward this data to the service layer that translates the data into appropriate queries for your database. So the answer would be you will need to have the information on both layers, but "handle" the data (e.g. if you need formation) in the controller.

syn
  • 96
  • 4
0

IMHO paging should be managed at the service level for the following reasons:

  1. A same data service could potentially be called by N different controllers: putting the paging logic on every controller would obviously lead to some code repetition (that you should avoid)

  2. There exist some other kinds of service clients than view/controllers: Think for instance about a background scheduled task needing to browse a potentially large quantity of records. It would be very handy for this batch to get the paging info directly from the service layer.

In Spring Data, the data services (eg the "repository" layer) are returning page rather than list. Any client of these data services can so benefit from the meta-information with the paging info.

Nice simple example:

https://mmarcosab.medium.com/a-simple-example-of-pagination-with-spring-data-jpa-605ed4c5b7f4

TacheDeChoco
  • 3,683
  • 1
  • 14
  • 17