How can Spring Boot implement pagination for data querying?
在SpringBoot中,可以使用Spring Data JPA提供的PagingAndSortingRepository接口来实现分页查询。
Firstly, extend the PagingAndSortingRepository interface in your Repository interface and specify the entity class and primary key type. For example, if you want to perform pagination queries on an entity called User, you can create a UserRepository interface like the following:
@Repository
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
}
Next, inject UserRepository into your Service class and use the Pageable interface to specify pagination parameters. Pageable interface has many implementation classes, with the most commonly used being PageRequest class. You can create a PageRequest object, specifying the page number, number of items per page, and sorting criteria.
@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);
}
}
The getUsers method in the above code takes three parameters: pageNo to indicate the page number to query, pageSize to represent the amount of data per page, and sortBy for the sorting rule. A PageRequest object is created and used to query with userRepository.findAll(pageable) method.
Finally, you can call the getUsers method from the UserService in the Controller layer to retrieve pagination data and send it back to the frontend.
@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);
}
}
The getUsers method in the above code accepts three optional request parameters: pageNo indicates the page number to be queried, defaulting to 0, pageSize indicates the amount of data per page, defaulting to 10, sortBy indicates the sorting rule, defaulting to sorting by id. Call the userService.getUsers method to retrieve paginated data and wrap it in a ResponseEntity object to return to the frontend.
By accessing the /users interface, you will be able to retrieve the results of a paginated query. For example, by accessing /users?pageNo=0&pageSize=10&sortBy=name, you will receive the first page with 10 data entries sorted by the name field.