在SpringBoot中,可以使用Spring Data JPA提供的PagingAndSortingRepository
接口來實現(xiàn)分頁查詢。
首先,在你的Repository接口中繼承PagingAndSortingRepository
接口,并指定實體類和主鍵類型。例如,如果你要對名為User
的實體進(jìn)行分頁查詢,可以創(chuàng)建一個UserRepository
接口如下:
@Repository
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}
接下來,在你的Service類中注入UserRepository
,并使用Pageable
接口來指定分頁參數(shù)。Pageable
接口有許多實現(xiàn)類,其中最常用的是PageRequest
類。你可以創(chuàng)建一個PageRequest
對象,指定頁數(shù)、每頁的數(shù)據(jù)量和排序規(guī)則。
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public Page<User> getUsers(int pageNo, int pageSize, String sortBy) {
Pageable pageable = PageRequest.of(pageNo, pageSize, Sort.by(sortBy));
return userRepository.findAll(pageable);
}
}
在上述代碼中,getUsers
方法接受三個參數(shù):pageNo
表示要查詢的頁數(shù),pageSize
表示每頁的數(shù)據(jù)量,sortBy
表示排序規(guī)則。創(chuàng)建了一個PageRequest
對象,并使用userRepository.findAll(pageable)
方法進(jìn)行查詢。
最后,你可以在Controller層調(diào)用UserService
中的getUsers
方法來獲取分頁數(shù)據(jù),并將其返回給前端。
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public ResponseEntity<Page<User>> getUsers(
@RequestParam(defaultValue = "0") int pageNo,
@RequestParam(defaultValue = "10") int pageSize,
@RequestParam(defaultValue = "id") String sortBy) {
Page<User> page = userService.getUsers(pageNo, pageSize, sortBy);
return ResponseEntity.ok(page);
}
}
上述代碼中,getUsers
方法接受三個可選的請求參數(shù):pageNo
表示要查詢的頁數(shù),默認(rèn)為0,pageSize
表示每頁的數(shù)據(jù)量,默認(rèn)為10,sortBy
表示排序規(guī)則,默認(rèn)按照id排序。調(diào)用userService.getUsers
方法獲取分頁數(shù)據(jù),并將其包裝在ResponseEntity
對象中返回給前端。
這樣,在訪問/users
接口時,就能獲取分頁查詢的結(jié)果了。例如,訪問/users?pageNo=0&pageSize=10&sortBy=name
,將返回第一頁、每頁10條數(shù)據(jù),按照name字段排序的結(jié)果。