This guide shows how to implement
pagination and sorting with
H2 database in
Spring Boot using Spring Data JPA.
1. Add Dependencies
In
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
2. Configure H2
In
application.properties
:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
3. Create Entity
import jakarta.persistence.*;
@Entity
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
}
4. Repository with Paging
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
}
5. Service for Pagination and Sorting
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
@Service
public class BookService {
private final BookRepository repo;
public BookService(BookRepository repo) {
this.repo = repo;
}
public Page<Book> getBooks(int page, int size, String sortBy) {
Pageable pageable = PageRequest.of(page, size, Sort.by(sortBy));
return repo.findAll(pageable);
}
}
6. REST Controller
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.Page;
@RestController
@RequestMapping("/books")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@GetMapping
public Page<Book> list(@RequestParam int page,
@RequestParam int size,
@RequestParam String sortBy) {
return service.getBooks(page, size, sortBy);
}
}
7. Test Pagination and Sorting
Run the app and try:
http://localhost:8080/books?page=0&size=5&sortBy=title
You’ll get the first 5 books sorted by title.
image quote pre code