springboot jpa paging query methods (two types)! ! !

springboot jpa paging query methods (two types)

    • 1.PagingAndSortingRepository interface
  • 2. @Query annotation custom query method
  • Summarize

This article introduces two commonly used methods for Spring Data JPA paging queries.

1. PagingAndSortingRepository interface

Insert image description here

Create a Repository interface that inherits from PagingAndSortingRepository, and use agreed naming rules on method names to define query methods. Spring Data JPA will automatically generate query statements based on method names, and supports paging and sorting. For example:

public interface UserRepository extends PagingAndSortingRepository<User, Long> {
    Page<User> find(Pageable pageable);
} 

Then in the Service layer, use the Pageable object to specify the paging information, and then call the method defined in the Repository to query. The code is as follows:

Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by("id").descending());
Page<User> users = userRepository.find(pageable); 

2. @Query annotation custom query method

Use the @Query annotation to customize the query method in the Repository interface. You can then write JPQL query statements or use native SQL queries, which is suitable for more complex queries.

public interface UserRepository extends JpaRepository<User, Long> {
    @Query("SELECT u FROM User u")
    Page<User> find(Pageable pageable);
} 

Pass in the Pageable object in the Service layer to implement paging query. The code is as follows:

Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by("id").descending());
Page<User> users = userRepository.find(25, pageable); 

Summarize

Both of the above methods can implement paging queries based on Spring Data JPA and can be used according to actual needs.
I hope it is helpful to you who read this article.