I was reading this paragraph in the Spring Data JPA official documentation about the difference between Page
and Slice
(emphasis mine):
The first method lets you pass an org.springframework.data.domain.Pageable instance to the query method to dynamically add paging to your statically defined query. A Page knows about the total number of elements and pages available. It does so by the infrastructure triggering a count query to calculate the overall number. As this might be expensive (depending on the store used), you can instead return a Slice. A Slice only knows about whether a next Slice is available, which might be sufficient when walking through a larger result set.
I get it how a Page
can get the total elements by executing an additional count query with the same where clause, but how does a Slice
gets to know whether other elements are available or not with a single query? What is the SQL executed?
annotation to specify a custom JPQL or native SQL query. Spring Data JPA provides the required JPA code to execute the statement as a JPQL or native SQL query. Your preferred JPA implementation, such as, Hibernate or EclipseLink, will then execute the query and map the result.
Slice is a sized chunk of data with an indication of whether there is more data available. Spring supports Slice as a return type of the query method. Pageable parameter must be specified by the same query method. Slice avoids triggering a count query to calculate the overall number of pages as that might be expensive.
In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.
Select Query In order to define SQL to execute for a Spring Data repository method, we can annotate the method with the @Query annotation — its value attribute contains the JPQL or SQL to execute. The @Query annotation takes precedence over named queries, which are annotated with @NamedQuery or defined in an orm.xml file.
How does a Slice gets to know whether other elements are available or not with a single query?
Spring Data JPA selects one element more than actually needed to fill the Slice
if that additional element is present, there is another Slice
available. If not this is the last Slice
.
See the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With