Best Division

Spread Your Knowledge

  • All topics
  • About us
  • Contact us
  • Privacy policy
  • Terms of service
  • Copyright
  • Facebook
  • Twitter
  • Instagram
  • Youtube
  • LinkedIn
  • Pinterest
  • Github
  • Tumblr

© 2026 Best Division

How do you implement pagination with native queries in JPA?

Java
Jayant Kumar
Jayant Kumar@jayantkumar314
PublishedDec 4, 2024
UpdatedNov 16, 2026
6 min read

To paginate a native SQL query in JPA, pass a Pageable to a Spring Data repository method annotated with @Query(nativeQuery = true) and give it an explicit countQuery. Without Spring Data, call setFirstResult and setMaxResults on the Query returned by EntityManager.createNativeQuery.

Note that @NativeQuery is not part of the JPA specification. It is a Spring Data JPA convenience annotation in recent versions that is equivalent to @Query(nativeQuery = true); the older form works in every version, so the examples use it.

Table of Contents

  • Native query pagination with Spring Data JPA
  • Why a countQuery is required
  • Sorting in native queries
  • Mapping results to DTOs
  • Pagination with EntityManager only
  • Keyset pagination in native SQL
  • Frequently Asked Questions
    • Is @NativeQuery part of JPA?
    • Why does my native paginated query fail without countQuery?
    • Can I use Pageable sort with native queries?
    • Does pagination work the same on every database?
  • Summary

Native query pagination with Spring Data JPA

Declare the method with a Pageable parameter and tell Spring Data how to count:

java

Calling it:

java

Spring Data runs the native query with setFirstResult(offset) and setMaxResults(size). Hibernate then adds the right clause for the configured database dialect, such as limit ? offset ? on PostgreSQL and MySQL or offset ? rows fetch first ? rows only on SQL Server and Oracle.

Text blocks (the triple-quoted strings) need Java 15 or later, which every currently supported Spring Boot release satisfies.

Why a countQuery is required

For JPQL, Spring Data derives the count query by rewriting the query. It cannot reliably do that for arbitrary native SQL, so a Page return type without countQuery fails at startup or at runtime with an error about the count query. Provide one that:

  • uses the same from and where clauses,
  • omits order by (it only slows the count),
  • omits columns and unneeded joins.

If you return Slice<T> or List<T>, no count query is run and countQuery is not needed.

Sorting in native queries

The Sort inside a Pageable is limited for native queries. Spring Data cannot safely rewrite arbitrary SQL, and sorting by an entity property name does not map to a column name. Two safe options:

  1. Write a fixed order by in the SQL and pass PageRequest.of(page, size) with no sort, as above.
  2. Accept an allow-listed sort key and choose between separate queries or a case expression.

Never concatenate user-supplied sort text into SQL; that is an injection risk. Native query parameters (:department) are bound safely, but identifiers such as column names cannot be bound.

Mapping results to DTOs

Native queries do not have to return entities. Use an interface projection with aliases that match the getter names:

java
java

Aliases are case-sensitive in some databases, so quote them or keep them in the case the database returns. Spring Data 3 and later also supports record-based DTO projections for many query types, but interface projections are the most dependable choice for native queries.

Pagination with EntityManager only

Without Spring Data, use createNativeQuery and the same two methods:

java

The count returns different Java types per database (Long, BigInteger, BigDecimal), so read it as Number.

Keyset pagination in native SQL

When a native query exists for performance, offset paging often undermines it. Keyset pagination uses a where filter on the last seen key:

java

This works on indexed columns in constant time per page. For multi-column ordering, compare tuples, for example (hire_date, id) < (:lastDate, :lastId), where your database supports row-value comparison.

Frequently Asked Questions

Is @NativeQuery part of JPA?

No. JPA defines @NamedNativeQuery and EntityManager.createNativeQuery. @NativeQuery is a Spring Data JPA shortcut in recent versions; @Query(nativeQuery = true) works in all of them.

Why does my native paginated query fail without countQuery?

Spring Data cannot derive a count query from arbitrary SQL. Add a countQuery or return Slice or List.

Can I use Pageable sort with native queries?

Only in limited cases. Write the order by in the SQL yourself and avoid passing user-controlled sort fields into it.

Does pagination work the same on every database?

Yes from your code's perspective. Hibernate generates the dialect-specific limit, offset or fetch first syntax.

Summary

For native queries, add nativeQuery = true, a matching countQuery and a fixed order by with a unique tiebreaker. Use projections instead of entities when you only need a few columns, read counts as Number in plain JPA, and prefer keyset pagination for deep pages.

Share