Joona Ritva
Joona Ritva

Reputation: 143

How to Add Pagination to a List Custom Query in JPA?

my repository looks like this:

public interface HeroRepository extends JpaRepository<Hero,Long>{
     @Query(value = "SELECT h.heroname , SUM(h.killCount) AS killcount FROM Heroes AS h GROUP BY h.heroname ORDER BY h.heroname",nativeQuery = true)     
     List<IHero> findAllHeroByGroupName();
}

How do I add pagination to a custom query that doesnt use the default "findAll" queries by JPA?

How do I tell Spring to convert this to a Page or pageable object?

findAllHeroByGroupName()

so that in my AppController I can use it like this:

Page page = heroService.findAllHeroByGroupName(pageNum);

Take note, that findAllHeroByGroupName() returns a List and not a Page object.

Upvotes: 1

Views: 5051

Answers (1)

Mohsin M
Mohsin M

Reputation: 259

You need to use Pageable

You method in repository class would look like:

public interface HeroRepository extends JpaRepository<Hero,Long>{
     @Query(value = "SELECT h.heroname , SUM(h.killCount) AS killcount FROM Heroes AS h GROUP BY h.heroname ORDER BY h.heroname",nativeQuery = true)     
     List<IHero> findAllHeroByGroupName(Pageable pageable);
}

Now to fetch the records using Pagination, You can use something like:

Pageable firstPageWithTwoElements = PageRequest.of(0, 2);

The first argument is pagenumber and second argument is size. You can read more about PageRequest

List<IHero> allProducts = heroRepository.findAllHeroByGroupName(firstPageWithTwoElements);

The findAll(Pageable pageable) method by default returns a Page<T> object.

However, we can choose to return either a Page<T>, a Slice<T>, or a List<T> from any of our custom methods returning paginated data.

Read more about how to to use Native queries here

Upvotes: 2

Related Questions