Pagination and Sorting with Spring Boot, ThymeLeaf, Spring Data JPA, Hibernate, MySQL

3 min read 4 hours ago
Published on Sep 30, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will implement pagination and sorting in a Spring Boot application using ThymeLeaf, Spring Data JPA, Hibernate, and MySQL. This builds upon our previous CRUD web application, enhancing the user experience by allowing users to navigate through large datasets efficiently.

Step 1: Set Up Your Development Environment

  • Ensure you have the following installed:
    • Java 8 or higher
    • Spring Boot
    • MySQL Database
    • Maven
  • Clone the source code from the GitHub repository:
    git clone https://github.com/RameshMF/springboot-thymeleaf-crud-pagination-sorting-webapp.git
    

Step 2: Configure Application Properties

  • Open the application.properties file in your Spring Boot project.
  • Configure your MySQL database connection:
    spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
    spring.datasource.username=your_username
    spring.datasource.password=your_password
    spring.jpa.hibernate.ddl-auto=update
    spring.jpa.show-sql=true
    

Step 3: Create the Entity Class

  • Define a JPA entity class that represents the data model. For example:
    @Entity
    public class Product {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String name;
        private double price;
    
        // Getters and Setters
    }
    

Step 4: Create the Repository Interface

  • Create a repository interface for your entity that extends JpaRepository:
    public interface ProductRepository extends JpaRepository<Product, Long> {
        Page<Product> findAll(Pageable pageable);
    }
    

Step 5: Implement the Service Layer

  • Create a service class that handles business logic and interacts with the repository:
    @Service
    public class ProductService {
        @Autowired
        private ProductRepository productRepository;
    
        public Page<Product> findPaginated(int page, int size) {
            Pageable pageable = PageRequest.of(page, size);
            return productRepository.findAll(pageable);
        }
    }
    

Step 6: Create the Controller

  • Implement a controller to handle requests and return the paginated and sorted data:
    @Controller
    public class ProductController {
        @Autowired
        private ProductService productService;
    
        @GetMapping("/products")
        public String listProducts(Model model,
                                   @RequestParam(defaultValue = "0") int page,
                                   @RequestParam(defaultValue = "10") int size) {
            Page<Product> productPage = productService.findPaginated(page, size);
            model.addAttribute("productPage", productPage);
            return "products"; // ThymeLeaf template
        }
    }
    

Step 7: Create the ThymeLeaf Template

  • Create a ThymeLeaf template (products.html) to display the paginated data:
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Price</th>
        </tr>
        <tr th:each="product : ${productPage.content}">
            <td th:text="${product.id}"></td>
            <td th:text="${product.name}"></td>
            <td th:text="${product.price}"></td>
        </tr>
    </table>
    <div>
        <span th:text="'Page ' + ${productPage.number} + ' of ' + ${productPage.totalPages}"></span>
        <a th:href="@{products(page=${productPage.number - 1}, size=${productPage.size})}" 
           th:if="${productPage.hasPrevious()}">Previous</a>
        <a th:href="@{products(page=${productPage.number + 1}, size=${productPage.size})}" 
           th:if="${productPage.hasNext()}">Next</a>
    </div>
    

Step 8: Enable Sorting

  • Modify the repository and service to handle sorting:
    public Page<Product> findPaginatedSorted(int page, int size, String sortField, String sortDir) {
        Pageable pageable = PageRequest.of(page, size, sortDir.equals("asc") ? Sort.by(sortField).ascending() : Sort.by(sortField).descending());
        return productRepository.findAll(pageable);
    }
    

Conclusion

You have successfully implemented pagination and sorting in your Spring Boot application using ThymeLeaf. This enhances the user experience by allowing users to navigate through data efficiently. As a next step, consider adding filtering options or enhancing the user interface further. For additional resources, check the blog post or the GitHub repository linked above.