Welcome, in this tutorial, we will understand the sorting in a spring boot application and for this, we will use thymeleaf.
Before going further in this tutorial, we will look at the common terminology such as introduction to Spring Boot, Lombok, Thymeleaf, and Sorting.
1.1 Spring Boot
Spring boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or, Undertow). Thus, no need to deploy the war files
It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them into the application
It helps in removing the boilerplate code, extra annotations, and XML configurations
It provides a powerful batch processing and manages the rest endpoints
It provides an efficient jpa-starter library to effectively connect the application with the relational databases
It offers a Microservice architecture and cloud configuration that manages all the application related configuration properties in a centralized manner
Lombok is nothing but a small library which reduces the amount of boilerplate Java code from the project
Automatically generates the getters and setters for the object by using the Lombok annotations
Hooks in via the Annotation processor API
Raw source code is passed to Lombok for code generation before the Java Compiler continues. Thus, produces properly compiled Java code in conjunction with the Java Compiler
Under the target/classes folder you can view the compiled class files
Can be used with Maven, Gradle IDE, etc.
1.2.1 Lombok features
Local variables are declared as final
Mutable local variables
Creates an SLF4J logger
Will call close() on the resource in the finally block
Creates getter methods for all properties
Creates setter for all non-final properties
Generates implementations of equals(Object other) and hashCode()
By default will use all non-static, non-transient properties
Can optionally exclude specific properties
Generates String of class name, and each field separated by commas
Optional parameter to include field names
Optional parameter to include a call to the super toString method
Generates no-args constructor
Will cause compiler error if there are final fields
Can optionally force, which will initialize final fields with 0/false/null var – mutable local variables
Generates a constructor for all fields that are final or marked @NonNull
The constructor will throw a NullPointerException if any @NonNull fields are null val – local variables are declared final
Generates a constructor for all properties of the class
No constructor is generated if constructors have been explicitly declared
Implements the Builder pattern for object creation
The immutable variant of @Data
All fields are made private and final by default
Thymeleaf is a server-side java template engine for the web applications
It processes the HTML, XML, JS, CSS, and simple text to bring the elegant designing to a web application
To use Thymeleaf, you must define the spring-boot-starter-thymeleaf dependency in the pom.xml and mention the xmlns:th="https://thymeleaf.org" library in the templates
Sorting is a process of retrieving the data in the ascending or the descending based on a given field
To perform pagination and sorting in a spring boot application we will use the PagingAndSortingRepository interface to provide the additional methods to sort the results either in the ascending or the descending order
2. Spring Boot sorting with Thymeleaf Tutorial
Here is a systematic guide for implementing this tutorial but before going any further I’m assuming that you are aware of the Spring boot basics.
2.1 Application Pre-requisite
To start with this tutorial, we are hoping that you at present have the Lombok plugin installed in the IDE of their favorite choice. If someone needs to go through the Lombok installation on IntelliJ IDE, please watch this video. For installation on Eclipse IDE, please watch this video.
2.2 Tools Used and Project Structure
We are using Eclipse Kepler SR2, JDK 8, and Maven. In case you’re confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.
Let us start building the application!
3. Creating a Spring Boot application
Below are the steps involved in developing the application.
3.1 Maven Dependency
Here, we specify the dependency for the Spring Boot, Spring Data JPA, Thymeleaf, H2 database, Faker, and Lombok. Maven will automatically resolve the other dependencies. The updated file will have the following code.
Let us write all the java classes involved in this application.
3.3.1 Implementation/Main class
Add the following code to the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication annotation and the static main method.
// Causes Lombok to generate toString(), equals(), hashCode(), getter() & setter(), and Required arguments constructor in one go.
// Causes Lombok to implement the Builder design pattern for the POJO class.
// Usage can be seen in DefaultEmployeesLoader.java -> createNewEmployee() method.
// Causes Lombok to generate a constructor with no parameters.
// Causes Lombok to generate a constructor with 1 parameter for each field in your class.
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "first_name", nullable = false)
@Column(name = "last_name", nullable = false)
@Column(name = "gender")
@Column(name = "email", nullable = false)
@Column(name = "phone_number", unique = true)
@Column(name = "home_address")
3.3.3 Configuration class
Add the following code to the bean class that will return the bean object for the faker object. The usage of this object can be seen in the DefaultEmployeesLoader.java class which is used to load the dummy data into the database on the application startup.
Add the following code to the controller class designed to handle the incoming requests. The class is annotated with the @Controller annotation were the HTTP GET method would return the index page of the application.
We will create a simple HTML page that will display the employees on the browser in smaller chunks (i.e. the paginated approach) and will support the sorting. Create a new HTML file at the location: SpringbootThymeleafPaginationSortingV2/src/main/resources/templates/ and add the following code to it.
To execute the application, right-click on the SpringbootThymeleafPaginationSorting.java class, Run As -> Java Application.
6. Project Demo
Open the browser of your choice and hit the following URL. The result will be displayed in a paginated manner (i.e. smaller chunks) and you can click on the page number to retrieve the results as per the page number.