How to implement pagination in SpringBoot?
In Spring Boot, you can achieve pagination query using Spring Data JPA. The specific steps are as follows:
- Please turn to the next page.
- Can be paginated
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);
}
- The ability to be paged or turned one at a time.
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);
}
}
- In the Controller, receive pagination parameters and invoke the Service layer method to retrieve paginated data. For example:
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);
}
}
By following the steps above, pagination functionality can be implemented in Spring Boot. The front-end page can display pagination data and navigation buttons based on the returned Page object.