java 99 lines · 2 tabs

Pagination and sorting with Spring Data

David Kumar Jan 2026
2 tabs
package com.example.demo.controller;

import com.example.demo.dto.PageResponse;
import com.example.demo.dto.UserDTO;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class PaginatedUserController {

    private final UserService userService;

    public PaginatedUserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping
    public ResponseEntity<PageResponse<UserDTO>> getUsers(
        @PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC)
        Pageable pageable
    ) {
        Page<User> page = userService.findAll(pageable);
        PageResponse<UserDTO> response = PageResponse.of(
            page.map(this::toDto)
        );
        return ResponseEntity.ok(response);
    }

    @GetMapping("/search")
    public ResponseEntity<PageResponse<UserDTO>> searchUsers(
        @RequestParam String query,
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "10") int size,
        @RequestParam(defaultValue = "name") String sortBy,
        @RequestParam(defaultValue = "ASC") String sortDir
    ) {
        Sort.Direction direction = Sort.Direction.fromString(sortDir);
        Pageable pageable = PageRequest.of(page, size, Sort.by(direction, sortBy));

        Page<User> results = userService.search(query, pageable);
        PageResponse<UserDTO> response = PageResponse.of(
            results.map(this::toDto)
        );
        return ResponseEntity.ok(response);
    }

    @GetMapping("/active")
    public ResponseEntity<PageResponse<UserDTO>> getActiveUsers(Pageable pageable) {
        Page<User> page = userService.findByActive(true, pageable);
        return ResponseEntity.ok(PageResponse.of(page.map(this::toDto)));
    }

    private UserDTO toDto(User user) {
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setName(user.getName());
        dto.setEmail(user.getEmail());
        return dto;
    }
}
2 files · java Explain with highlit

Spring Data provides elegant pagination and sorting mechanisms. Pageable interface defines page number, size, and sort parameters. Page wraps results with metadata—total elements, total pages, current page. Sort defines ordering by multiple properties. I use @PageableDefault for sensible defaults. Query methods accept Pageable automatically. Custom queries support pagination with Pageable parameters. DTOs should include pagination metadata for API clients. Offset-based pagination works for most cases; cursor-based pagination handles large datasets better. Sorting prevents inconsistent results across pages. Pagination reduces memory usage and improves response times. REST controllers use @RequestParam or Spring's automatic resolution. Proper pagination enhances user experience and system performance.


Related snips

ruby
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)

Turbo Frames: infinite scroll with lazy-loading frame

rails turbo hotwire
by codesnips 4 tabs
graphql
type User {
    id: ID!
    name: String!
    email: String!
    posts: [Post!]!
    createdAt: String!

GraphQL API with Spring Boot

java graphql spring-boot
by David Kumar 3 tabs
java
package com.example.starter.config;

import com.example.starter.properties.CustomProperties;
import com.example.starter.service.CustomService;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;

Custom Spring Boot starters

java spring-boot starter
by David Kumar 4 tabs
java
package com.example.demo.config;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

Messaging with Apache Kafka

java kafka messaging
by David Kumar 3 tabs
ruby
module Paginatable
  extend ActiveSupport::Concern

  MAX_PER_PAGE = 100
  DEFAULT_PER_PAGE = 25

API Pagination Headers (Link + Total)

rails pagination rest-api
by codesnips 3 tabs
java
package com.example.demo.controller;

import com.example.demo.dto.FileMetadata;
import com.example.demo.service.FileStorageService;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;

File upload and download handling

java spring-boot file-upload
by David Kumar 2 tabs

Share this code

Here's the card — post it anywhere.

Pagination and sorting with Spring Data — share card
Link copied