How to implement paging and sorting with Spring Boot?

Using Spring Boot to implement paging and sorting requires Spring Data JPA. Spring Data JPA is a module in the Spring Data project that provides functionality to simplify the data access layer, including paging and sorting.

Next, we use a piece of Java code to show how to use Spring Data JPA and Spring Boot to implement paging and sorting:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    
  
  @Autowired
  private UserRepository userRepository;
  
  public Page<User> getUsers(int pageNumber, int pageSize, String sortBy) {
    
    
    PageRequest pageRequest = PageRequest.of(pageNumber, pageSize, Sort.by(sortBy));
    return userRepository.findAll(pageRequest);
  }
  
}

The above code shows a UserService, which has a getUsers method that accepts three parameters: page number, page size, and sorting attributes. This method uses the findAll method of Spring Data JPA, which uses the PageRequest object for paging and sorting settings. In this example, the sort property is set using the Sort.by method.

1682474520327_SpringBoot implements paging and sorting.jpg

In UserRepository, you only need to inherit JpaRepository, and you don't need to implement any methods, because Spring Data JPA will automatically generate CRUD methods for us.

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    
    

}

The above code shows UserRepository, which inherits JpaRepository, which provides many commonly used CRUD methods.

When in use, we can call the getUsers method of UserService as follows:

@RestController
public class UserController {
    
    

  @Autowired
  private UserService userService;

  @GetMapping("/users")
  public Page<User> getUsers(@RequestParam("page") int pageNumber,
                             @RequestParam("size") int pageSize,
                             @RequestParam("sort") String sortBy) {
    
    
    return userService.getUsers(pageNumber, pageSize, sortBy);
  }
  
}

The code above shows a UserController that handles the /users path with a GET request and calls the UserService's getUsers method to get a list of users. In request parameters we can pass page number, page size and sorting properties.

The above is a basic example of Spring Boot paging and sorting. I hope it can help you understand how to use Spring Boot to implement paging and sorting.

Guess you like

Origin blog.csdn.net/cz_00001/article/details/131835627