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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...