Using lazy data retrieval in Thymeleaf

January 04, 2020 No comments Lazy Data Thymeleaf

1. Introduction

In this article, we will present the techniques of data retrieving optimalization in Thymeleaf. We will focus on lazy mechanism wchich allows to save the time for unnecessary downloading data that will not be displayed on the resulting page.

2. Overview

Thymeleaf is a template engine for Java-based web and standalone applications. It is commonly used library to generate dynamic HTML, JS and create reports on the back-end side.

3. Lazy data loading

Sometimes there is a need to optimize the retrieving data process in our application. When the time of rendering the website is important we should think about a lazy loading mechanism. Fortunately, Thymeleaf offers a lazily load context variables. Variables that implement ILazyContextVariable interface will be resolved only in the moment of being executed.

In the following example we will wrap user data with LazyContextVariable object and put them into the app context (Model) under users key.

import org.thymeleaf.context.LazyContextVariable;

@GetMapping("users")
public String main(Model model) {

    model.addAttribute("users", new LazyContextVariable<List<User>>() {
        @Override
        protected List<User> loadValue() {
            return userService.getUsers();
        }
    });

    return "users";
}

As you can see below, we can work with the template without the knowledge about laziness nature of the given variable. To iterate over users collection (that implements ILazyContextVariable interface) use th:each attribute just like for any other collection:

<ul>
  <li th:each="user : ${users}">
     <th:block th:text="${user.username}">Username</th:block>
  </li>
</ul>

The main profit is achieved when the ${condition} evaluates to false. In that case load Value() method of Lazy Context Variable will never be called, so we don't need to retrieve data from repositories and send them throughout the application layers.

<ul th:if="${condition}">
  <li th:each="user : ${users}">
     <th:block th:text="${user.username}">Username</th:block>
  </li>
</ul>

4. Conclusion

In this article, we presented the lazy loading mechanism available in Thymeleaf. It works in a transparent way. Lazy variables will be resolved only if they are needed and actually being rendered on the result website.

As usual a working version of the code shown in this article is available in our GitHub Repository.

{{ message }}

{{ 'Comments are closed.' | trans }}