title: How to Add Pagination to Custom JPA Query?
body: <p>I know how to use Pagination when using default JPA-provided queries like &quot;findAll&quot;, etc. (BASIC)
  However, I created my own Custom Query in my repository:</p>
  <pre><code>public interface HeroRepository extends JpaRepository&lt;Hero,Long&gt;{
       @Query(value = &quot;SELECT h.heroname , SUM(h.killCount) AS killcount FROM Heroes AS h GROUP BY h.heroname ORDER BY h.heroname&quot;,nativeQuery = true)     
       List&lt;IHero&gt; findAllHeroByGroupName();
  }
  </code></pre>
  <p>Now I dont know how to add Pagination with custom queries and use custom Pageable implementation. This is what I have so far and it's not fetching anything from DB. It says &quot;0&quot; results when I log it. So nothing is displayed on my front-end.</p>
  <p><strong>Repository:</strong></p>
  <pre><code>public interface HeroRepository extends JpaRepository&lt;Hero,Long&gt;{
  
  @Query( value = &quot;SELECT h.heroname , SUM(h.killCount) FROM Heroes AS h GROUP BY h.heroname ORDER BY h.heroname #{#pageable}&quot;,nativeQuery = true)     
          Page&lt;IHero&gt; findAllHeroByGroupName(Pageable pageable);
  }
  </code></pre>
  <p><strong>Service:</strong></p>
  <pre><code>public Page&lt;IHero&gt; findAllHeroByGroupName(int pageNum) {    
      Pageable pageable = PageRequest.of(pageNum, 10);    
      return  agentRepository.findAllHeroByGroupName(pageable);   
  }
  </code></pre>
  <p><strong>Controller:</strong></p>
  <pre><code>    private List&lt;IHero&gt; heroList = new ArrayList&lt;&gt;();
     
      @GetMapping(&quot;/hero&quot;)
      public String goToHeroPage(Model model) {
              return viewHeroPage(model, 1);
      }
      
      @GetMapping(&quot;/heropage/{pageNum}&quot;)
      public String viewHeroPage(Model model, 
              @PathVariable(name = &quot;pageNum&quot;) int pageNum) {
          
           Page&lt;IHero&gt; page = heroService.findAllHeroByGroupName(pageNum);
           System.out.println(&quot;heroList SIZE &quot;+heroList.size());
          
           model.addAttribute(&quot;currentPage&quot;, pageNum);        
           model.addAttribute(&quot;totalPages&quot;, page.getTotalPages());
           model.addAttribute(&quot;totalItems&quot;, page.getTotalElements());
  
           model.addAttribute(&quot;heroList&quot;, page.getContent() );
           return &quot;heropage&quot;;
      }   
  </code></pre>
  <p>When I check the <code>heroList.size()</code>, it says &quot;0&quot;. When Im using the old query (top most code), everything is working fine (but I need pagination).</p>
  <p>So How can I add pagination to my custom JPA query?</p>