Spring Boot, Thymeleaf, Hibernate, JPA, Maven, and MySQL Database

In this tutorial, we will learn how to develop a Spring MVC web application using Spring Boot, Thymeleaf, Hibernate, JPA, Maven, and MySQL database.

What we’ll build

We are building a simple Spring MVC web application using Thymeleaf as a view.
Output: HTML page using Thymeleaf which displays a list of users from MySQL database.

1. Create Spring Boot Project

There are many ways to create a Spring Boot application. The simplest way is to use Spring Initializr at http://start.spring.io/, which is an online Spring Boot application generator.

2. Maven Dependencies

Add below Maven dependencies to your Spring Boot project:

        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
        </dependency>

3. Packaging Structure

Here is the project structure for your reference:

4. Create a JPA Entity - User

Let's create a User JPA entity with the following content into it:
import jakarta.persistence.*;

@Entity
@Table(name = "user")
public class User
{
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
 
    public User()
    {
    }

    public User(Integer id, String name)
    {
         this.id = id;
         this.name = name;
    }

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }
}

5. Create Spring Data JPA Repository - UserRepository

Let's create UserRepository interface that extends JpaRepository interface:
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Integer>
{

}

6. Create Spring Controller - HomeController

Let's create HomeController Spring MVC controller with home() handler method that returns index Thyemelaf view:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController
{
    @Autowired UserRepository userRepo;
 
    @RequestMapping("/")
    public String home(Model model)
    {
        model.addAttribute("users", userRepo.findAll());
        return "index";
    }
}

7. Configuring MySQL Database

Configure application.properties to connect to your MySQL database. 

Let's open an application.properties file and add the following database configuration to it.
logging.level.org.springframework=INFO

################### DataSource Configuration ##########################
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/users_database
spring.datasource.username=root
spring.datasource.password=root

################### Hibernate Configuration ##########################

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

message.properties

Create a message.properties under the resources folder and add the following content to it - 

app.title=SpringMVC JPA Demo (With SpringBoot)

8. Insert SQL Script

Once you will run this application will create users table in a database and use the below insert SQL script to populate a few records in a users table.
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('1', 'Salman');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('2', 'SRK');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('3', 'AMIR');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('4', 'Tiger');
INSERT INTO `users_database`.`user` (`id`, `name`) VALUES ('5', 'Prabhas');

9. Create a Thymeleaf View - index.html

Let's create a Thymeleaf view to show the list of users. Locate the index.html file under src/main/resources/templates folder of this project.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" 
   xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Home</title>
</head>
<body>
 <h2 th:text="#{app.title}">App Title</h2>
    <table>
        <thead>
         <tr>
           <th>Id</th>
           <th>Name</th>
        </tr>
        </thead>
        <tbody>
          <tr th:each="user : ${users}">
             <td th:text="${user.id}">Id</td>
             <td th:text="${user.name}">Name</td>
          </tr>
        </tbody>
    </table>
 </body>
</html>

10. Running the Application

Now run Spring boot application and hit this link in the browser: http://localhost:8080/
You will see below HTML page on the screen:

11. Source code on GitHub

The source code of this tutorial is available on my GitHub Repository.

Comments

  1. you didnt mention about db details...
    which version of my sql is used...

    ReplyDelete
    Replies
    1. Hi, I updated MySQL version in tools and technologies used section. Spring boot starter parent provides default property for MySQL version that is 5.1.46

      Delete
    2. spring.datasource.url=jdbc:mysql://localhost:3306/users_database?autoReconnect=true&useSSL=false

      if its not mention autoReconnect=true&useSSL=false it shown as warm error message....

      what is autoReconnect=true&useSSL=false ? can you explain about this?

      Delete
  2. Thanks you for this great tutorial! but I'm curious where app.title is from.

    ReplyDelete
    Replies
    1. Create a message.properties under resource folder and add the following content to it - app.title=SpringMVC JPA Demo (With SpringBoot). Refer source code project on my GitHub repository.

      Delete
  3. you have to create a messages.properties and add it to that. It is in the same directory as your application.properties.

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Leave Comment