https://github.com/maemresen/spring-pagination-example
Discover Spring Data pagination: optimal querying for complex relationships, accurate strategies, and practical examples. Elevate your projects with robust pagination techniques.
https://github.com/maemresen/spring-pagination-example
best-practices code-examples entity-relationship hibernate java-persistence-api pagination spring-data
Last synced: 3 months ago
JSON representation
Discover Spring Data pagination: optimal querying for complex relationships, accurate strategies, and practical examples. Elevate your projects with robust pagination techniques.
- Host: GitHub
- URL: https://github.com/maemresen/spring-pagination-example
- Owner: maemresen
- Created: 2023-02-02T16:01:54.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-02-02T16:28:16.000Z (over 2 years ago)
- Last Synced: 2025-01-11T18:28:47.225Z (4 months ago)
- Topics: best-practices, code-examples, entity-relationship, hibernate, java-persistence-api, pagination, spring-data
- Language: Java
- Homepage:
- Size: 5.86 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Introduction;
When you want to apply pagination with using Spring Data, you could define a method in your repository something as follows;````java
public interface ...extends JpaRepository<...>{// method 1
Page<...>findSomeTastyData(...);// method 2 with using HQL
@Query("HQL to fetch data")
Page<...>findSomeTastyData(...);// method 3: you could also use some custom count query
@Query(
value = "HQL to fetch data"
countQuery = "HQL to count data"
)
Page<...>findSomeTastyData(...);}
````# Problem
Let's assume we have two entity as follows;
- Book [see](./src/main/java/com/maemresen/springpaginationexample/entity/Book.java)
- Chapter [see](./src/main/java/com/maemresen/springpaginationexample/entity/Chapter.java)**Where** one book having many chapters.\
So there are `OneToMany` relation between `Book` and `Chapter` entities.Now, again, assume that we need to query book as following
We will have a query something as follows;````java
public interface BookRepository extends JpaRepository {@Query("SELECT b FROM Book b LEFT JOIN b.chapters WHERE ....")
Page getBooks(Pageable pageable);
}
````But what happens if we do something like this;
````java
public interface BookRepository extends JpaRepository {@Query(
value = "SELECT b FROM Book b LEFT JOIN b.chapters WHERE ....",
countQuery = "SELECT b FROM Book b"
)
Page getBooks(Pageable pageable);
}
````As you can see, query contains `LEFT JOIN` where count query not.
# Testing
After clone and build application, check the following API
### API
- **URI:** `/book`
- **Params:**
- page: page number (index based, starts from 0)
- size: page sizeExample API call to get first page with size 1;
```
http://localhost:8080/book?page=0&size=1
```