Let's say we have an entity called MyEntity
. It is possible to query pageable results using @Query
and with named queries, e.g.
@Query(value = "select e from MyEntity e where e.enabled = true")
Page<MyEntity> findAllEnabled(Pageable pageable);
However, it is not possible to achieve the same with native query, so this
@Query(value = "select * from my_entity where enabled = true", nativeQuery = true)
Page<MyEntity> findAllEnabled(Pageable pageable);
won't work.
What are the reasons behind this? Is it possible to make Pageable working with native queries?
This is description, given in spring data jpa documentation (http://docs.spring.io/spring-data/jpa/docs/1.8.0.M1/reference/html/)
JPQL abstracts SQL implementation and it's providers specifics, and makes it responsibility of ORM framework to generate correct SQL.
So by using Pagination in JPQL form, Spring just needs to generate correct JPQL, and it will be interpreted on ORM level to correct SQL.
While doing so with SQL, would imply that Spring knows how to generated correct SQL for the vast majorities of RDBMS, duplicating ORM functionality, which is too much overhead.
I don't know if this is still relevant to you: At least in Spring Data JPA 1.9.4 you can specify two queries.
Given a repository:
You can add 2 native queries to your entity, one for the query itself and one for the count statement:
The trick is to specify the count query with the suffix
.count
. This works also with the Spring Data@Query
annotation.Notice that you need a SQL result set mapping for the count query, though.
This works actually pretty nice.
There is a way to use Pageable with native queries with the SpEL capacity of Spring data, it is mention here.
You can find an example in this repository.
The sort functionnality will not work properly if there is a subquery in the
from
clause or your native query and you wish to apply a dynamic sort on it. The way it can be done is to move the subquery in thewhere
clause.Spring data will append to the end of your request
" order by "
if there is aSort
object in thePageable
. (with Spring data 1.10.3)A better way is to convert the native query in jpql if possible.