SpringBoot整合JPA的分頁查詢可以通過使用Spring Data JPA提供的Pageable
接口來實(shí)現(xiàn)。首先,需要在Repository接口中定義一個(gè)方法,方法的返回類型為Page<T>
,其中T
為查詢的實(shí)體類,方法的參數(shù)中可以傳入一個(gè)Pageable
對(duì)象來指定分頁的參數(shù),例如:
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
Page<User> findAll(Pageable pageable);
}
然后在Service層中調(diào)用Repository中定義的方法,并傳入一個(gè)PageRequest
對(duì)象來指定分頁的參數(shù),例如:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page<User> getUsers(int page, int size) {
PageRequest pageable = PageRequest.of(page, size);
return userRepository.findAll(pageable);
}
}
最后,在Controller層中調(diào)用Service中定義的方法并返回分頁查詢的結(jié)果,例如:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@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.getUsers(page, size);
}
}
通過以上步驟,就可以實(shí)現(xiàn)SpringBoot整合JPA的分頁查詢功能。在前端調(diào)用接口時(shí),可以傳入page
和size
參數(shù)來控制分頁查詢的頁數(shù)和每頁數(shù)據(jù)量。