简体   繁体   中英

Spring Data JPA Pagination without count query

According to Spring docs https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.special-parameters returning with List should not issue count query.

But with my spring it goes kinda strange.

When running page request with page 1 it works without count query which i suppose is right.

请求第 1 页

But when I invoke repository with page 2 (or above) suddenly it does a count query after select query which I didn't expect.

要求第 2 页或以上

Is there any way that I could make count query not issued with using Pageable?

Repository and service code for what i did.

@Repository
public interface ArticleRepository extends CrudRepository<Article, Long> {
  // Slice was also tested and did issue count query from page 2
  List<Article> findAll(Pageable pageable);
} 

@Service
public class ArticleService {
  private final ArticleRepository articleRepository;

  @Autowired
  public ArticleService(
      ArticleRepository articleRepository) {
    this.articleRepository = articleRepository;
  }

  public List<Article> getArticles(int page) {
    PageRequest pageRequest = PageRequest.of(page, 50, Sort.by("createdAt").descending());
    return articleRepository.findAll(pageRequest);
  }
}

If you need to extend CrudRepository, then you will be able to define method with Slice in your repository:

Slice<Article> findAll(Pageable pageable);

I think that other option is change the super interface to PagingAndSortingRepository . It can solve the use of List on the return.

interface ArticleRepository extends PagingAndSortingRepository<Article, Long> {
    List<Article> findAll(Pageable pageable);
}
  1. you can compose PagingAndSortingRepository and CrudRepository as they both are interfaces or use JpaRepository instead.
  2. you can write your own count query by setting it into @Query annotation.

in source code for public Page<T> findAll(Pageable pageable) there is totalSupplier which executes count query to get total number.

if (content.size() != 0 && pageable.getPageSize() > content.size()) {
    return new PageImpl<>(content, pageable, pageable.getOffset() + content.size());
}
return new PageImpl<>(content, pageable, totalSupplier.getAsLong());

So you cannot avoid it with default repository method. Specify you own jpa method or declare query annotation under PagingAndSortingRepository class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM