溫馨提示×

SpringBoot中怎么實現(xiàn)分頁查詢

小億
214
2024-03-08 10:40:30
欄目: 編程語言

在Spring Boot中,可以使用Spring Data JPA來實現(xiàn)分頁查詢。具體步驟如下:

  1. 在Repository接口中定義一個方法,使用Spring Data JPA提供的Page接口和Pageable接口來實現(xiàn)分頁查詢。例如:
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. 在Service層中調(diào)用Repository中定義的方法,并傳入Pageable對象來指定分頁參數(shù)。例如:
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中接收分頁參數(shù),并調(diào)用Service層的方法來獲取分頁數(shù)據(jù)。例如:
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中實現(xiàn)分頁查詢功能。在前端頁面中可以根據(jù)返回的Page對象來展示分頁數(shù)據(jù)和分頁導(dǎo)航按鈕。

0