Pagination and Sorting in SpringBoot RESTful Web Services

Follow this tutorial
http://appsdeveloperblog.com/rest-pagination-tutorial-with-spring-mvc/
https://dzone.com/articles/conditional-pagination-and-sorting-using-restful-w

Step 1: Dao Layer extends  PagingAndSortingRepository
@Repository
public interface PaginationDao extends PagingAndSortingRepository<PagingEntity, Integer> {

}
Step 2: Service Layer 
@Service
public class PaginationService {

 @Autowired
 private PaginationDao paginationDao;

 public Page findJsonDataByCondition(String orderBy, String direction, int page, int size) {

  Sort sort = null;

  if (direction.equals("ASC")) {
   sort = new Sort(new Sort.Order(Direction.ASC, orderBy));
  }

  if (direction.equals("DESC")) {
   sort = new Sort(new Sort.Order(Direction.DESC, orderBy));
  }

  Pageable pageable = new PageRequest(page, size, sort);

  Page data = paginationDao.findAll(pageable);

  return data;

 }

}

Step 3: Controller layer
@RestController
@RequestMapping(value = "/pagination")
public class PaginationController {
 @Autowired
 private PaginationService paginationService;
 
 @RequestMapping(value = "/conditionalPagination", params = { "orderBy", "direction", "page", "size" }, method = RequestMethod.GET)
 @ResponseBody
 public Page findJsonDataByPageAndSize(@RequestParam("orderBy") String orderBy,
 @RequestParam("direction") String direction, @RequestParam("page") int page,
 @RequestParam("size") int size) {
  if (!(direction.equals(Direction.ASCENDING.getDirectionCode())
  || direction.equals(Direction.DESCENDING.getDirectionCode()))) {
   throw new PaginationSortingException("Invalid sort direction");
  }
  if (!(orderBy.equals(OrderBy.ID.getOrderByCode()) || orderBy.equals(OrderBy.USERID.getOrderByCode()))) {
   throw new PaginationSortingException("Invalid orderBy condition");
  }
  
  Page list = paginationService.findJsonDataByCondition(orderBy, direction, page, size);
  
  return list;
 }
 
}

Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch