SpringBootでのページネーション検索の実装方法は何ですか?

Spring Boot内で、Spring Data JPAを使用してページネーション機能を実装することができます。具体的な手順は以下の通りです:

  1. ページ (Pēji)
  2. ページャブル
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<User, Long> {
    Page<User> findAll(Pageable pageable);
}
  1. ページャブル
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Page<User> findAllUsers(int page, int size) {
        PageRequest pageable = PageRequest.of(page, size);
        return userRepository.findAll(pageable);
    }
}
  1. Controller内でページネーションパラメーターを受け取り、Service層のメソッドを呼び出してページネーションデータを取得します。例えば:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.domain.Page;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/users")
    public Page<User> getUsers(@RequestParam(defaultValue = "0") int page, 
                               @RequestParam(defaultValue = "10") int size) {
        return userService.findAllUsers(page, size);
    }
}

Spring Bootの中で、ページネーション機能を実装するには、上記の手順に従う必要があります。 フロントエンドページでは、返されたPageオブジェクトを使用して、ページデータとページナビゲーションボタンを表示することができます。

bannerAds