But when I invoke repository with page 2
(or above) suddenly it does a count query after select query which I didn't expect.
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);
}
}
CodePudding user response:
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);
}
CodePudding user response:
- you can compose PagingAndSortingRepository and CrudRepository as they both are interfaces or use JpaRepository instead.
- 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.