0Pricing
Spring Boot 4 Microservices & REST APIs · บทเรียน

การแบ่งหน้าและการเรียงลำดับ

เพิ่มความสามารถในการแบ่งหน้าและเรียงลำดับให้ REST endpoint เพื่อดึงข้อมูลได้อย่างมีประสิทธิภาพ

การแบ่งหน้าและการเรียงลำดับ เป็นบทเรียน Spring Boot 4 Microservices & REST APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Spring Boot 4 Microservices & REST APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Handling Large API Responses

Imagine an API returning thousands of database records. Fetching all that data at once is inefficient and can overwhelm both the server and the client.

  • Slow Performance: Large payloads take longer to transfer and process.
  • High Resource Usage: Both client and server use more memory and CPU.
  • Poor User Experience: Users might wait a long time or see a frozen app.

This is where pagination comes in handy!

What is Pagination?

Pagination is a technique to divide a large set of results into smaller, manageable chunks called 'pages'. Instead of getting everything, you request one page at a time.

  • Page Number: Which page you want (e.g., page 1, page 2).
  • Page Size: How many items should be on each page (e.g., 10 items per page).

This significantly improves API performance and user experience by reducing data transfer.

Spring Data's Pageable

Spring Data JPA provides a convenient Pageable interface to handle pagination and sorting requests. When you include Pageable as a method parameter in your controller, Spring automatically extracts the pagination (and sorting) information from the request parameters.

Common query parameters used by Spring are page (0-indexed) and size.

Implementing Pagination

Let's create a simple Spring Boot REST endpoint that returns a paginated list of items. We'll use @PageableDefault to set default page and size values.

Run this application and access http://localhost:8080/api/items?page=0&size=3 in your browser.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.ArrayList;

@SpringBootApplication
@RestController
public class PagingController {

    private List<String> items = List.of("Apple", "Banana", "Orange", "Grape", "Kiwi", "Mango", "Peach", "Plum", "Cherry", "Lemon", "Fig", "Date");

    @GetMapping("/api/items")
    public Page<String> getItems(
        @PageableDefault(size = 3, page = 0) Pageable pageable) {

        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), items.size());

        List<String> pagedItems = items.subList(start, end);
        return new PageImpl<>(pagedItems, pageable, items.size());
    }

    public static void main(String[] args) {
        SpringApplication.run(PagingController.class, args);
    }
}

Exploring Paged Responses

When you call the API from the previous scene, try these URLs:

  • http://localhost:8080/api/items (uses defaults: page 0, size 3)
  • http://localhost:8080/api/items?page=0&size=5 (first page, 5 items)
  • http://localhost:8080/api/items?page=1&size=3 (second page, 3 items)

Notice how the response includes not just the content, but also metadata like totalPages, totalElements, and number (current page number).

Why Sorting Matters

Just as important as limiting the data is presenting it in a meaningful order. Users often want data sorted by name, date, price, or other attributes.

For example, a list of products might be sorted alphabetically, by price (low to high), or by creation date (newest first). APIs should provide this flexibility.

Sorting with Pageable

The good news is that Spring Data's Pageable also handles sorting! You can specify sorting criteria directly in your API request.

  • Field Name: The property to sort by (e.g., name, price).
  • Direction: Whether to sort ascending (asc) or descending (desc).

The standard query parameter for sorting is sort=fieldName,direction.

Implementing Sorting

Let's extend our item API to support sorting. We'll add a default sort order to @PageableDefault.

Run this application and access http://localhost:8080/api/items/sorted?page=0&size=3&sort=item,asc in your browser.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;

@SpringBootApplication
@RestController
public class SortingController {

    private List<String> items = new ArrayList<>(List.of("Apple", "Banana", "Orange", "Grape", "Kiwi", "Mango", "Peach", "Plum", "Cherry", "Lemon", "Fig", "Date"));

    @GetMapping("/api/items/sorted")
    public Page<String> getSortedItems(
        @PageableDefault(size = 3, page = 0, sort = "item", direction = Sort.Direction.ASC) Pageable pageable) {

        Comparator<String> comparator = Comparator.naturalOrder();
        if (pageable.getSort().isSorted() && pageable.getSort().getOrderFor("item") != null) {
            Sort.Direction direction = pageable.getSort().getOrderFor("item").getDirection();
            if (direction == Sort.Direction.DESC) {
                comparator = Comparator.reverseOrder();
            }
        }
        items.sort(comparator);

        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), items.size());

        List<String> pagedAndSortedItems = items.subList(start, end);
        return new PageImpl<>(pagedAndSortedItems, pageable, items.size());
    }

    public static void main(String[] args) {
        SpringApplication.run(SortingController.class, args);
    }
}

Combining Sort & Page

You can combine pagination and sorting in a single request! The Pageable object handles both seamlessly.

Try these URLs with the running application:

  • http://localhost:8080/api/items/sorted?page=0&size=4&sort=item,desc (first page, 4 items, descending)
  • http://localhost:8080/api/items/sorted?page=1&size=2&sort=item,asc (second page, 2 items, ascending)

This flexibility allows clients to retrieve exactly the data they need, how they need it.

Quick Check: API Parameters

You're building an API to list products. You want to retrieve the third page, with 10 products per page, sorted by price in descending order. Which of the following query parameters would achieve this?

Recap: Pagination & Sorting

We've learned how to implement pagination and sorting in Spring Boot REST APIs, making them more efficient and user-friendly.

  • Pagination: Use page (0-indexed) and size to retrieve data in chunks.
  • Sorting: Use sort=fieldName,direction (e.g., asc or desc) to order results.
  • Spring Data's Pageable: A powerful interface that automatically handles these parameters when included in your controller methods.

These techniques are crucial for building robust APIs that can handle large datasets gracefully.

คำถามที่พบบ่อย

บทเรียน “การแบ่งหน้าและการเรียงลำดับ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การแบ่งหน้าและการเรียงลำดับ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Spring Boot 4 Microservices & REST APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Spring Boot 4 Microservices & REST APIs มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การแบ่งหน้าและการเรียงลำดับ”

เพิ่มความสามารถในการแบ่งหน้าและเรียงลำดับให้ REST endpoint เพื่อดึงข้อมูลได้อย่างมีประสิทธิภาพ คุณปฏิบัติ Spring Boot 4 Microservices & REST APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Spring Boot 4 Microservices & REST APIs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Spring Boot 4 Microservices & REST APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 3 บทเรียน

บทเรียน “การแบ่งหน้าและการเรียงลำดับ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Spring Boot 4 Microservices & REST APIs นี้ได้ไหม

ได้ บทเรียน Spring Boot 4 Microservices & REST APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การตรวจสอบคำขอและการตอบกลับ
  2. การแบ่งหน้าและการเรียงลำดับ
  3. หลักการ HATEOAS สำหรับ REST
← กลับไปที่ Spring Boot 4 Microservices & REST APIs