Home Spring boot Spring boot Thymeleaf Crud Application

Spring boot Thymeleaf Crud Application

17 min read
0
10
41,625

This  tutorial will teach you spring boot crud example with jpa mysql. how to do the basic database functions that are CREATE RETIEVE UPDATE and DELETE using spring boot crud application with thymeleaf and hibernate. The INSERT, SELECT, UPDATE and DELETE statements can be used in any database system, because this is support by all relational database systems. spring boot application is good demand in the software industry.

We will learn how to INSERT, SELECT, UPDATE and DELETE in database by writing code to manage the student table in the database named lindaschool student table consist of following columns studentname,course,fee.
crud java spring boot Screen shot i attached image below.how to create the spring boot crud web application step by step
let’s learn.if you want learn spring boot with angular 12 crud example click here

Let’s Start the Project Step by Step

The package structure, you must following the standard package structure of spring boot and spring framework. For the example i have created the project name emp

com.example.emp
|
-------------------->EmpApplication.java
com.example.emp.service
|
--------------------->StudentService
com.example.emp.controller
|
----------------------> StudentController.java
com.example.emp.repository
|
-----------------------> StudentRepository.java
com.example.emp.domain
|
------------------------>Student.java

Attached the Folder Structure

When you create the Spring boot application by default EmpApplication.java is created this class has the main method

package com.example.emp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EmpApplication {

    public static void main(String[] args) {
        SpringApplication.run(EmpApplication.class, args);
    }

}

How to Spring Boot Application Architecture works Learn here

Create the package com.example.emp.service . inside the package you have to create the class StudentService.java.

StudentService.java

package com.example.emp.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.emp.domain.Student;
import com.example.emp.repository.StudentRepository;

@Service
public class StudentService {
    
    @Autowired
    private StudentRepository repo;
    
    public List<Student> listAll() {
        return repo.findAll();
    }
     
    public void save(Student std) {
        repo.save(std);
    }
     
    public Student get(long id) {
        return repo.findById(id).get();
    }
     
    public void delete(long id) {
        repo.deleteById(id);
    }

}

After that you have to Create the package com.example.emp.controller . inside the package you have to create the class Student Controller.java.

Student Controller.java

package com.example.emp.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 org.springframework.web.servlet.ModelAndView;

import com.example.emp.domain.Student;
import com.example.emp.service.StudentService;

@Controller
public class StudentController {
    
     @Autowired
        private StudentService service;

        @GetMapping("/")
        public String viewHomePage(Model model) {
            List<Student> liststudent = service.listAll();
            model.addAttribute("liststudent", liststudent);
            System.out.print("Get / ");	
            return "index";
        }

        @GetMapping("/new")
        public String add(Model model) {
            model.addAttribute("student", new Student());
            return "new";
        }

        @RequestMapping(value = "/save", method = RequestMethod.POST)
        public String saveStudent(@ModelAttribute("student") Student std) {
            service.save(std);
            return "redirect:/";
        }

        @RequestMapping("/edit/{id}")
        public ModelAndView showEditStudentPage(@PathVariable(name = "id") int id) {
            ModelAndView mav = new ModelAndView("new");
            Student std = service.get(id);
            mav.addObject("student", std);
            return mav;
            
        }
        @RequestMapping("/delete/{id}")
        public String deletestudent(@PathVariable(name = "id") int id) {
            service.delete(id);
            return "redirect:/";
        }
}

After that you have to Create the package com.example.emp.repository inside the package you have to create the interface StudentRepository.java

StudentRepository.java

package com.example.emp.repository;

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

import com.example.emp.domain.Student;


@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

}

After that you have to Create the package com.example.emp.domain inside the package you have to create the class

Student.java

package com.example.emp.domain;

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

@Entity
public class Student {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;
    private String studentname;
    private String course;
    private int fee;
    public Student() {

    }
    public Student(Long id, String studentname, String course, int fee) {
    
        this.id = id;
        this.studentname = studentname;
        this.course = course;
        this.fee = fee;
    }
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getStudentname() {
        return studentname;
    }
    public void setStudentname(String studentname) {
        this.studentname = studentname;
    }
    public String getCourse() {
        return course;
    }
    public void setCourse(String course) {
        this.course = course;
    }
    public int getFee() {
        return fee;
    }
    public void setFee(int fee) {
        this.fee = fee;
    }

}

 

after that you have to create the index.html page inside the src/main/resources inside the package you have a templates folder inside the folder you must create the  index.html page.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/cosmo/bootstrap.min.css" />
    <script src= "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" ></script>
</head>
<body>
<div>
    <h2 >Spring Boot Crud System -Student Registation</h2>
    <tr>
        <div align = "left" >		   
             <h3><a  th:href="@{'/new'}">Add new</a></h3>     
        </div>
    
    </tr>
    <tr>
    
    <div class="col-sm-5" align = "center">
                 <div class="panel-body" align = "center" >
                 <table class="table">
  <thead class="thead-dark">
    <tr>
      		<th>Student ID</th>
            <th>Student Name</th>
            <th>Course</th>
            <th>Fee</th>
            <th>Edit</th>
            <th>Delete</th>
   	</tr>
  </thead>
  <tbody>
      <tr  th:each="student : ${liststudent }">
        <td th:text="${student.id}">Student ID</td>
        <td th:text="${student.studentname}">StudentName</td>
        <td th:text="${student.course}">Course</td>
        <td th:text="${student.fee}">Fee</td>				
        <td>
            <a th:href="@{'/edit/' + ${student.id}}">Edit</a>
        </td>							    
        <td>
            <a th:href="@{'/delete/' + ${student.id}}">Delete</a>
        </td>		    
        </tr> 
   
  </tbody>
</table>
                    
                 </div>

            </div> 

    </tr>

    </tbody>
    </table>
    <div>
</body>
</html>

 

Inside the folder create the another file new.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
    <title>Create New Product</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootswatch/4.5.2/cosmo/bootstrap.min.css" />
    <script src= "https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" ></script>
</head>
<body>
<div align="center">
    <h1>Create New Student</h1>
    <br />
     <div class="col-sm-4">
    <form action="#" th:action="@{/save}" th:object="${student}" method="post">

      
 		<div alight="left">
            <tr>
                <label class="form-label" >Student Name</label>
                <td>
                    <input type="hidden" th:field="*{id}" />
                    <input type="text" th:field="*{studentname}" class="form-control" placeholder="Student Name" />
                </td>
            </tr>
         </div>   
            
          	<div alight="left">
          
            <tr>
                 <label class="form-label" >Course</label>
                <td><input type="text" th:field="*{course}" class="form-control" placeholder="Course" /></td>
            </tr>
            </div> 
            <div alight="left">
                 <tr>
                 <label class="form-label" >Fee</label>
                <td><input type="text" th:field="*{fee}" class="form-control" placeholder="Fee" /></td>
            </tr>
            </div> 
            <br>
            <tr>
            <td colspan="2"><button type="submit" class="btn btn-info">Save</button> </td>
            </tr>
        </table>
    </form>
</div>
</body>
</html>

After that you must set database path and project configuration in application.properties file

spring.datasource.url=jdbc:mysql://localhost:3306/lindaschool?useUnicode=true&useJDBCCompliantTimezone
Shift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
server.error.whitelabel.enabled=false
server.port=7050
spring.datasource.username=root
spring.datasource.password=

spring.jpa.open-in-view=false
spring.thymeleaf.cache=false
api.base.path = http://localhost:7050  // this the port i set where tomcat run

Related Tutorials

Spring boot with Angular Full Stack Project
https://www.tutussfunny.com/spring-boot-with-angular-full-stack-project/

Spring boot with React Full Stack Project
https://www.tutussfunny.com/spring-boot-with-react-full-stack-project/

Spring boot with Vue js Full Stack Project
https://www.tutussfunny.com/spring-boot-with-vue-js-full-stack-project/

Spring boot with MongoDB Crud Application
https://www.tutussfunny.com/spring-boot-with-mongodb-crud-application/

Spring boot with Angular MongoDB database Full Stack Project
https://www.tutussfunny.com/spring-boot-with-angular-mongodb-database-full-stack-project/

Spring boot with React MongoDB database Full Stack Project
https://www.tutussfunny.com/spring-boot-with-react-mongodb-database-full-stack-project/

 

Load More Related Articles
Load More By admin
Load More In Spring boot

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also

Inventory management system using React

In today’s fast-paced business environment, an efficient inventory management system…