DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Trending

  • Using Java Stream Gatherers To Improve Stateful Operations
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • A Guide to Auto-Tagging and Lineage Tracking With OpenMetadata
  • Agile’s Quarter-Century Crisis
  1. DZone
  2. Data Engineering
  3. Data
  4. Simple Pagination Example With Spring Data and Thymeleaf

Simple Pagination Example With Spring Data and Thymeleaf

Need help with pagination?

By 
Oguzhan Dogan user avatar
Oguzhan Dogan
·
Dec. 19, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
55.8K Views

Join the DZone community and get the full member experience.

Join For Free

As some of you know, pagination is used to display big result sets. Sometimes, it's hard to list all the data at once. In these cases, pagination techniques are used to divide and display the big result set. In this tutorial, I'll try to show you a simple pagination example with Spring Boot, Spring Data, and Thymeleaf.

For this tutorial, I use a sample Article CRUD web application, which I designed previously.

First of all, I chose Spring Boot 2.0.5.RELEASE, MySQL, Spring Data, and Thymeleaf for the Article CRUD application.

So before starting, you need to have these dependencies, aside from the usual Spring Boot dependencies.

<dependency>
    <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>


A POJO is created for the Article entity, as shown below:

@Entity
@Table(name = "article")
public class Article {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private long id;
    @Column(name = "url")
    private String url;
    @Column(name = "status")
    private String status;

  //getters and setters
}


A DAO interface, which extends from the CrudRepository, is created. This is what makes difference.

public interface ArticleDao extends CrudRepository<Article, Long> {
    Page<Article> findAll(Pageable pageable);
}


For listing articles with pagination, a Controller method is created:

    @RequestMapping(value = "/article-list/page/{page}")
    public ModelAndView listArticlesPageByPage(@PathVariable("page") int page) {
        ModelAndView modelAndView = new ModelAndView("article-list-paging");
        PageRequest pageable = PageRequest.of(page - 1, 15);
        Page<Article> articlePage = articleService.getPaginatedArticles(pageable);
        int totalPages = articlePage.getTotalPages();
        if(totalPages > 0) {
            List<Integer> pageNumbers = IntStream.rangeClosed(1,totalPages).boxed().collect(Collectors.toList());
            modelAndView.addObject("pageNumbers", pageNumbers);
        }
        modelAndView.addObject("activeArticleList", true);
        modelAndView.addObject("articleList", articlePage.getContent());
        return modelAndView;
    }


You can see that the Spring Data PageRequest object (org.springframework.data.domain.PageRequest) is used in the controller. I preferred to pass page size as static but I strongly recommend you read it from the properties file. I passed this PageRequest object to a method in theArticleService. Let's see what is inside this service method.

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleDao articleDao;

@Override
    public Page<Article> getPaginatedArticles(Pageable pageable) {
        return articleDao.findAll(pageable);
    }
}


In thegetPaginatedArticles method, the  findAll(Pageable pageable) method in ArticleDao is called.  ArticleDao's findAll method returns the records sorted by ID using page and page size, which we provided in thePageRequest object. 

In the end, we have the Page<Article>  object in the controller. We retrieve the list of Article by calling the getContent() method of thePageobject.  And below, you can see how the article list is displayed and how pagination is done with the help of Thymeleaf.

    <div class="row" th:fragment="article-list" th:if="${articleList != null && !articleList.isEmpty()}">
        <div class="col-md-2"></div>
        <div class="col-md-8">
            <table id="link-list" class="table table-striped table-bordered" style="width:100%">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>URL</th>
                    <th>Status</th>
                    <th>Detail</th>
                </tr>
                </thead>
                <tbody>
                <tr th:each="article : ${articleList}">
                    <td th:text="${{article.id}}">1</td>
                    <td th:text="${{article.url}}">http://thegame.org</td>
                    <td th:text="${{article.status}}">PENDING</td>
                    <td><a th:href="@{/article/detail/{articleId}(articleId=${article.id})}">Detail</a></td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="col-md-2"></div>
    </div>

<div class="row" th:fragment="pagination">
        <div class="col-md-2"></div>
        <div class="col-md-8">
            <nav aria-label="Pagination">
                <ul class="pagination justify-content-center">
                    <li class="page-item" th:each="pageNumber : ${pageNumbers}" >
                        <a class="page-link" th:href="@{|/article-list/page/${pageNumber}|}" th:text=${pageNumber}>1</a>
                    </li>
                </ul>
            </nav>
        </div>
        <div class="col-md-2"></div>
    </div>


That's all! 

Conclusion

Now, we have a sample pagination example. I know that there are some unhandled errors in it, but it's up to you to use and improve upon this example. There're lots of techniques and methods for pagination. I only wanted to give an example today

Happy coding!

Spring Framework Spring Data Data (computing) Thymeleaf

Opinions expressed by DZone contributors are their own.

Related

  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Less Code With Spring Data Rest
  • Calling Stored Procedures With IN and OUT Parameters From Spring Data JPA
  • Spring Data: Easy MongoDB Migration Using Mongock

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!