在Spring Boot中,可以使用Spring Data JPA來實現分頁查詢。具體步驟如下:
Page
接口和Pageable
接口來實現分頁查詢。例如: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);
}
Pageable
對象來指定分頁參數。例如: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);
}
}
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
對象來展示分頁數據和分頁導航按鈕。