Skip to main content

Spring Boot Crud Operation with Thymeleaf, JPA and MySql Database | Step by Step

Spring Boot application with Thymeleaf, Rest API, JPA and MySql Database

Spring Boot Crud Operation with Thymeleaf + MySql + JPA

In this article, we will seen how to create simple Spring boot application with Create, Read, Update and Delete operations with MySql and Thymeleaf.

But first checkout what is Thymeleaf?

Thymeleaf :-

Thymeleaf is modern server side Java template engine for web and standalone environment. Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

So lets start our Tutorial :-

First learn how to create Spring Boot application with Rest API, JPA and Mysql. 

Project Structure :-

spring boot crud with thymeleaf + mysql + jpa project structure

For Create Spring Boot project and Sql table click on Above given link.

1. Configure Maven Dependency

For work with Thymeleaf we have to include "spring-boot-starter-thymeleaf" Dependency. 

We are also adding "mysql-connector-java" dependency for connecting web application with MySql database.

pom.xml

<?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.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringBootCrudWithThymeleaf</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootCrudWithThymeleaf</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </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>
            </plugin>
        </plugins>
    </build>

</project>

2. Add application.properties file

In application.properties file, we will define Mysql database connection properties.

  • datasource url
  • datasource driverClassName
  • datasource username
  • datasource password
We also can define how table will create every time when application starts. Here we are using update. update property creates table only first time and insert new record based on old data.

spring.datasource.url = jdbc:mysql://localhost:3306/test?useSSL=false
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.username = root
spring.datasource.password = root

#The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto = update

3. Create Model Class

package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "book")
public class Book {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    
    @Column
    private String bookname;
    
    @Column
    private String author;
    
    @Column
    private int price;
    
    public int getId() {
        return id;
    }

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

    public String getBookname()    {
        return bookname;
    }
    
    public void setBookname(String bookname) {
        this.bookname = bookname;
    }
    
    public String getAuthor() {
        return author;
    }
    
    public void setAuthor(String author) {
        this.author = author;
    }
    
    public int getPrice() {
        return price;
    }
    
    public void setPrice(int price) {
        this.price = price;
    }
}

3. Create Repository Interface

package com.example.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.model.Book;

public interface BookRepository extends JpaRepository<Book, Integer> {

}

 

4. Create Service class

package com.example.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.model.Book;
import com.example.repository.BookRepository;

@Service
public class BookService {

    @Autowired
    BookRepository bookRepository;

    public List<Book> loadAllBooks() {
        return (List<Book>) bookRepository.findAll();
    }

    public Book loadBookById(int id) {
        return bookRepository.findById(id).get();
    }
    
    public Book saveBook(Book book) {
        bookRepository.save(book);
        return loadBookById(book.getId());
    }

    public void deleteBook(int id) {
        bookRepository.deleteById(id);
    }
    
    public Book updateBook(Book book) {
        return bookRepository.save(book);
    }

}

5. Create Controller class

package com.example.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.example.model.Book;
import com.example.service.BookService;

@Controller
@RequestMapping("/books")
public class BookController {

    @Autowired
    BookService bookService;

    @RequestMapping( method = RequestMethod.GET)
    private String getAllBooks(Model model) {
        List<Book> list = bookService.loadAllBooks();
        model.addAttribute("allBooks", list);
        return "index";
    }
    
    @RequestMapping("/new")
    public String showNewBookPage(Model model) {
        Book book = new Book();
        model.addAttribute("book", book);
        return "add-book";
    }
    
    @RequestMapping(path = "/save", method = RequestMethod.POST)
    public String saveNewBook(@ModelAttribute("book") Book book) {
        bookService.saveBook(book);
        return "redirect:/books";
    }

    @GetMapping("/edit/{id}")
    private String editBook(@PathVariable("id") int id, Model model) {
        Book book = bookService.loadBookById(id);
        model.addAttribute("book", book);
        return "edit-book";
    }
    
    @RequestMapping(path = "/update/{id}", method = RequestMethod.POST)
    private String updateBook(@PathVariable("id") int id, @ModelAttribute Book book) {
        book.setId(id);
        bookService.updateBook(book);
        return "redirect:/books";
    }

    @GetMapping("/delete/{id}")
    private String deleteBook(@PathVariable("id") int id) {
        bookService.deleteBook(id);
        return "redirect:/books";
    }
}

Now we create index file that displays all books that are stored on our database. You can see in "getAllBooks()" method we returns a "index" as string means index.html page.

For run the project right click on project and click on Run As -> Spring Boot App

Enter http://localhost:8080/books in browser

Display or Read

index.html

<html xmlns:th="http://www.thymeleaf.org">
    <body>
        <div align="center">
            <a href="/books/new">
                <button>Add New Book</button>
            </a>
            <table border="1" cellpadding="5">
                <thead>
                    <tr>
                        <th>Book Name</th>
                        <th>Author Name</th>
                        <th>Price</th>
                        <th>Edit</th>
                        <th>Delete</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="book : ${allBooks}">
                        <td th:text="${book.bookname}"></td>
                        <td th:text="${book.author}"></td>
                        <td th:text="${book.price}"></td>
                        <td>
                            <a th:href="@{/books/edit/{id}(id=${book.id})}">Edit</a>
                        </td>
                        <td>
                            <a th:href="@{/books/delete/{id}(id=${book.id})}">Delete</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </body>
</html>

So lets see how its looks like

Display all data in spting boot crud with thymeleaf

Create or Add

add-book.html

<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Add New Book</title>
    </head>
    <body>
        <div align="center">
            <form action="#" th:action="@{/books/save}" th:object="${book}" method="post">
    
                <table border="0" cellpadding="10">
                    <tr>
                        <td>Book Name:</td>
                        <td><input type="text" th:field="*{bookname}" /></td>
                    </tr>
                    <tr>
                        <td>Author:</td>
                        <td><input type="text" th:field="*{author}" /></td>
                    </tr>
                    <tr>
                        <td>Price:</td>
                        <td><input type="text" th:field="*{price}" /></td>
                    </tr>                           
                    <tr>
                        <td colspan="2"><button type="submit">Save</button> </td>
                    </tr>
                </table>
            </form>
        </div>
    </body>
</html>

 

for add new book, click on Add New Book button.
spring boot save operation

Update

edit-book.html

<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Update Book</title>
    </head>
    <body>
        <div align="center">
            <form action="#" th:action="@{/books/update/{id}(id=${book.id})}" th:object="${book}" method="post">
    
                <table border="0" cellpadding="10">
                    <tr>
                        <td>Book Name:</td>
                        <td><input type="text" th:field="*{bookname}" /></td>
                    </tr>
                    <tr>
                        <td>Author:</td>
                        <td><input type="text" th:field="*{author}" /></td>
                    </tr>
                    <tr>
                        <td>Price:</td>
                        <td><input type="text" th:field="*{price}" /></td>
                    </tr>                           
                    <tr>
                        <td colspan="2"><button type="submit">Save</button> </td>
                    </tr>
                </table>
            </form>
        </div>
    </body>
</html>

In edit operation we update the "Head First Java" book price 1000 to 2000

Delete :-

For delete operation simply click on delete link and its done.

delete operation in spring boot with thymeleaf


If you have any query regrading above tutorial comment down.

See Related Article :-


Comments

  1. Thanks for sharing this article. However, I am asking you to please add user roles authorization.

    ReplyDelete
    Replies
    1. Thank you for reading and suggestion.
      I have added Authentication and Authorization using Spring Security, you can check out here.
      https://uniquethrowdown.blogspot.com/2021/11/authentication-and-authorization-in-spring-security.html

      Delete

Post a Comment

Popular posts from this blog

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last