This guide shows how to implement
pagination in a
Spring Boot project using the
Apache Derby database and Spring Data JPA.
1. Add Dependencies
In
pom.xml
:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2. Configure Derby
In
application.properties
:
spring.datasource.url=jdbc:derby:memory:demoDB;create=true
spring.datasource.driver-class-name=org.apache.derby.jdbc.EmbeddedDriver
spring.jpa.hibernate.ddl-auto=update
3. Create Entity
import jakarta.persistence.*;
@Entity
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String content;
// getters and setters
}
4. Repository with Paging
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface ArticleRepository extends JpaRepository<Article, Long>, PagingAndSortingRepository<Article, Long> {
}
5. REST Controller
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/articles")
public class ArticleController {
private final ArticleRepository repo;
public ArticleController(ArticleRepository repo) {
this.repo = repo;
}
@GetMapping
public Page<Article> getArticles(@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "5") int size) {
return repo.findAll(PageRequest.of(page, size));
}
}
6. Test Pagination
Run app:
mvn spring-boot:run
Request page 0 with 5 results:
curl "http://localhost:8080/articles?page=0&size=5"
Request page 1 with 5 results:
curl "http://localhost:8080/articles?page=1&size=5"
image quote pre code