Spring Boot Thymeleaf Display List of Records from Database




Hey guys in this post, we will discuss displaying the database records in Thymeleaf template in Spring boot application.

Overview


  • th:each is a thymeleaf special attribute, used to iteration over collections
  • th:text attribute evaluates the value expression and sets the value to the tag

Complete Example


We will create this example step by step, follow this tutorial till the end

Read More:

Create spring boot project


There are many different ways to create a spring boot application, you can follow the below articles to create one –

>> Create spring boot application using Spring initializer
>> Create spring boot application in Spring tool suite [STS]
>> Create spring boot application in IntelliJ IDEA

Add maven dependencies


Open pom.xml and add the following dependencies –

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.3</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>in.bushansirgur</groupId>
	<artifactId>springbootthymeleaf</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBootThymeleaf</name>
	<description>Spring boot thymeleaf web app for Employee Management</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<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>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>

spring-boot-starter-web dependency for building web applications using Spring MVC. It uses the tomcat as the default embedded container. spring-boot-devtools dependency for automatic reloads or live reload of applications. spring-boot-starter-thymeleaf dependency for using the thymeleaf template engine





lombok dependency is a java library that will reduce the boilerplate code that we usually write inside every entity class like setters, getters, and toString(). mysql-connector-java dependency is to store the data into the database.

Configure the datasource


Open application.properties file and add the following contents

spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb
spring.datasource.username=root
spring.datasource.password=scbushan05

spring.jpa.hibernate.ddl-auto=update

Create an Entity


Create Employee.java class inside in.bushansirgur.springbootthymeleaf.entity package and add the following content

package in.bushansirgur.springbootthymeleaf.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Entity
@Table(name="tbl_employees")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;
	
	private String name;
	
	private String email;
	
	private String department;
}

Create a Repository


Create EmployeeRepository.java interface inside in.bushansirgur.springbootthymeleaf.dao package and add the following content

package in.bushansirgur.springbootthymeleaf.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import in.bushansirgur.springbootthymeleaf.entity.Employee;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{

}

Create a Controller


Create EmployeeController.java class inside in.bushansirgur.springbootthymeleaf.controller package and add the following content

package in.bushansirgur.springbootthymeleaf.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import in.bushansirgur.springbootthymeleaf.dao.EmployeeRepository;

@Controller
public class EmployeeController {
	
	@Autowired
	private EmployeeRepository eRepo;
	
	@GetMapping({"/list", "/"})
	public ModelAndView getAllEmployees() {
		ModelAndView mav = new ModelAndView("list-employees");
		mav.addObject("employees", eRepo.findAll());
		return mav;
	}
}

We are adding the employees list to the ModelAndView so that we can access this list inside thymeleaf template.

Create view template


Create list-employees.html page inside the templates folder and add the following content

<html lang="en" xmlns:th="http://www.thymeleaf.org">
	
	<head>
		<title>List Employees</title>
		
		<link rel="stylesheet" 
			href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" 
			integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" 
			crossorigin="anonymous" />
	</head>
	
	<body>
		
		<div class="container">
		
			<h3>List Employees</h3>
			
			<hr/>
		
			<table class="table table-bordered table-striped">
			
				<thead>
					<tr>
						<th>Name</th>
						<th>Email</th>
						<th>Department</th>
					</tr>
				</thead>
				<tbody>
					<tr th:each="employee: ${employees}">
						<td th:text="${employee.name}" />
						<td th:text="${employee.email}" />
						<td th:text="${employee.department}" />
					</tr>
				</tbody>
				
			</table>
		</div>
		
		
	</body>
	
</html>

We are iterating the list employees using thymeleaf attribute th:each, each time loop runs thymeleaf creates temporary variable employee and we are printing the employee fields using thymeleaf attribute th:text

Run the app


Run the application using the below maven command –

mvn spring-boot:run

Open the Browser and enter the following URL –

  • localhost:8080/

Screenshot-2021-08-12-at-10-52-16-PM

That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.



Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

This Post Has One Comment

  1. My Name is Anthony

    Not working. Bad tutorial

Leave a Reply