Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Tutorial
  • Java Spring
  • Spring Interview Questions
  • Java SpringBoot
  • Spring Boot Interview Questions
  • Spring MVC
  • Spring MVC Interview Questions
  • Java Hibernate
  • Hibernate Interview Questions
  • Advance Java Projects
  • Java Interview Questions
Open In App
Next Article:
Employee Management System Project using Spring Boot
Next article icon

Employee Management System Project using Spring Boot

Last Updated : 04 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Employee Management System includes operations like adding new Employees into the Database, updating existing Employees, Delete Employees, Retrieving All Employees' Data in the form of a Table and the final one is Delete All Employees. In This Article, we will learn about Employee Management systems such as EMS App or EMS. Mostly This Spring boot web application handles the Employee data and performs different operations on each Employee record in the database.

Prerequisites:

To understand this Employee Management System application, you need basic knowledge of below technologies:

  • Spring Boot
  • Thymeleaf
  • MongoDB
  • Other Spring MVC Patterns
  • Bootstrap Framework

The Spring Boot is used for creating web applications with MVC pattern, Thymeleaf is used for generating dynamic HTML content in the web pages as well and the main purpose is integrating the HTML pages with Spring framework, and MongoDB is used for Data Storage.

Employee Data

In this Employee Management System Application, we collected Employee data with different fields like,

  • Employee ID
  • Employee Name
  • Employee Phone Number
  • Employee Gender
  • Employee Salary in Rupees
  • Employee Role

One more thing is the Employee ID is Dynamically Created and Map with other employee details and inserted into the database. In the Employee Management System, we have used the Bootstrap framework for responsive web designing and used models. The Bootstrap Model is Dynamic html Content, when clicking on the button dynamically the Model is Opened.

In this Web Application we can delete an employee by entering employee id and we can update an employee by providing new details of employee with existing employee id and other feature is we can able delete all the employees by entering yes, if you enter yes, the application decides to need to delete all the employee data. Now we will do these all things with coding for better understanding.

Requirements for Employee Management System using Spring Boot

  • Spring Boot
  • Thymeleaf ( reference )
  • MongoDB
  • Bootstrap
  • Knowledge about Spring MVC
  • Gradle
  • Spring Tool Suite IDE

Project Steps:

  1. Create a Spring Stater Project ( reference )
  2. create packages for controller, pojo, repository in main application package.
  3. In controller package create one EmployeeController class after that create an Employee POJO class in pojo package, after that create one EmployeeRepo Interface in repo package. After that create one html page in templates which is placed in project resource folder.
  4. Now Implement the Controller layer code, after that pojo class and other one interface also we need to implement.
  5. Once completed the back-end functionalities, then develop the Front-End web pages.
  6. After that Integrate both Back-End and Front-End by using Thymeleaf
  7. After that Run the entire project as Spring Boot App ( reference )

Project Dependencies:

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

Note: These Project Dependencies are available in build.gradle file once project is created. For this Project I used these Dependencies.

Project Folder Structure:

project-structure


Now I Will explain the coding part in different layers like Controller layer, Repository, POJO classes and other things. First we start with actual requirement, That is perform some operations on employee details. Before performing operation on employee details first we need employee details right. So I gather some details for employee like Employee ID, Employee Name, Employee Name, Employee Phone Number, Employee Gender, Employee Salary in Rupees And the last one Employee Role all these things. Now declare these fields in POJO class for performing setters and getters operations for every field.

Database Connection

In Spring boot, one file is there that is application.properties file which is used for database connection in this project. In this Project I used MongoDB. Based on that I write some properties in this file for database connection. You can observe that file in the above project folder structure picture.

# database properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=ems

# thymeleaf configuration
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

Model Layer

The Employee.java and ConfirmationForm.java comes under Model Layer which is used to controller the data flow in the application using these pojo classes in this project.

Employee.java

Employee.java is the class which contains all the details of employee and setters and getters methods for every field in the Employee java class as well as parameterized constructor and one default constructor I used in this POJO for different operations like data insertion and data update and data delete and others. And one dependency is available in spring boot that is lombok.

Java
package com.ems.app.pojo;  import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document;  @Data @AllArgsConstructor @NoArgsConstructor @Document(collection = "employee") public class Employee {      @Id private String id;     private String employeeName;     private String employeeEmail;     private Long employeePhone;     private String employeeGender;     private String employeeSalary;     private String employeeRole; } 


It is provide lot annotations but in this pojo I used @Data, @AllArgsConstructor, @NoArgsConstructor, @Document(collection="employee)". The @Data annotation is used for managing setters and getters methods as well as @AllArgsConstructor is used for managing parameterized constructor and @NoArgsConstructor is used for managing default constructor, @Document(collection="employee) is used for creating document in MongoDB.

ConfirmationForm.java

This Pojo class is used for conformation to delete all the employee's data by typing 'yes' in the text filed. If You Enter Yes in that text field, you conformed to delete all employee's data from the database. I will explain about this pojo class in controller layer for better understanding.

Java
package com.ems.app.pojo;  import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;  @Data @AllArgsConstructor @NoArgsConstructor public class ConfirmationForm {     private String confirmation; } 

View

Generally the HTML, JSP, and other front-end technologies are comes under View layer in Spring MVC. For this Employee Management System I used HTML as a View for displaying the Data to end users with the help of Thymeleaf. In this HTML page I created four Dynamic forms for handling the Application from front-end. every page performs a unique operation based on its use.

index.html

HTML
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org">  <head>     <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">     <link rel="shortcut icon" href="https://cdn-icons-png.flaticon.com/512/470/470199.png">     <meta charset="UTF-8">     <title>EMS App</title> </head>  <style>     body {         overflow-x: hidden;         scroll-behavior: smooth;     }      nav {         background-color: navy !important;      }      .navbar-brand {         color: whitesmoke !important;         font-size: 30px !important;         font-weight: bold;     }      .card {         box-shadow: rgba(14, 30, 37, 0.12) 1px 2px 2px 0px, rgba(14, 30, 37, 0.32) 1px 2px 2px 0px;     }      .card-body {         text-align: center;     }      .table-responsive {         box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 2px 6px 2px;     }      th {         text-align: center;         font-size: 18px !important;     }      td {         text-align: center;         font-size: 15px;         font-weight: 500;     }      label {         font-weight: 500;     } </style>  <body>      <nav class="navbar navbar-expand-sm navbar-light mb-5">         <div class="container">             <a class="navbar-brand text-bold" href="#"><i class="fa fa-align-center"                     aria-hidden="true">&nbsp;&nbsp;EMS</i></a>         </div>     </nav>      <main>         <div class="container p-4">             <div class="head_section">                 <div class="row row-cols-1 row-cols-md-4 g-3">                     <div class="col">                         <a href="#exampleModalToggle1" data-bs-toggle="modal" role="button"                             style="text-decoration: none; color: white;">                             <div class="card h-100 bg-success">                                 <div class="card-body">                                     <h5 class="text-light"><i class="fa fa-plus"></i>&nbsp;Add Employee</h5>                                 </div>                             </div>                         </a>                     </div>                     <div class="col">                         <a href="#exampleModalToggle2" data-bs-toggle="modal" role="button"                             style="text-decoration: none; color: white;">                             <div class="card h-100 bg-primary">                                 <div class="card-body">                                     <h5 class="text-light"><i class="fa fa-area-chart"                                             aria-hidden="true"></i>&nbsp;Update Employee</h5>                                 </div>                             </div>                         </a>                     </div>                     <div class="col">                         <a href="#exampleModalToggle3" data-bs-toggle="modal" role="button"                             style="text-decoration: none; color: white;">                             <div class="card h-100 bg-danger">                                 <div class="card-body">                                     <h5 class="text-light"><i class="fa fa-trash"></i>&nbsp;Delete Employee</h5>                                 </div>                             </div>                         </a>                     </div>                     <div class="col">                         <a href="#deleteAllModal4" data-bs-toggle="modal" role="button"                             style="text-decoration: none; color: white;">                             <div class="card h-100 bg-dark">                                 <div class="card-body">                                     <h5 class="text-light"><i class="fa fa-warning"></i>&nbsp;Delete All</h5>                                 </div>                             </div>                         </a>                     </div>                 </div>             </div>             <br>             <div class="items_table mt-5 mb-4">                 <div class="table-responsive p-2">                     <h4 class="text-center p-2 class=" p-1" mt-2"                         style="font-family:'Times New Roman', Times, serif; font-weight: bold;">Employee Management                         System</h4>                     <table class="table table-bordered table-hover mt-5">                         <thead class="bg-warning">                              <th>SI.NO</th>                             <th>ID</th>                             <th>Name</th>                             <th>Email</th>                             <th>Phone</th>                             <th>Gender</th>                             <th>Salary</th>                             <th>Role</th>                          </thead>                         <tbody>                             <tr th:each="employee, index : ${employees}">                                 <td th:text="${index.index + 1}"></td>                                 <td th:text="${employee.id}"></td>                                 <td th:text="${employee.employeeName}"></td>                                 <td th:text="${employee.employeeEmail}"></td>                                 <td th:text="${employee.employeePhone}"></td>                                 <td th:text="${employee.employeeGender}"></td>                                 <td th:text="${employee.employeeSalary}"></td>                                 <td th:text="${employee.employeeRole+' Developer'}"></td>                             </tr>                          </tbody>                     </table>                 </div>             </div>         </div>     </main>       <!-- model for create-->     <div class="modal fade" id="exampleModalToggle1" aria-hidden="true" aria-labelledby="exampleModalToggleLabel"         tabindex="-1">         <div class="modal-dialog modal-dialog-centered">             <div class="modal-content">                 <div class="modal-body">                     <div th:if="${success}" class="alert alert-success" role="alert">                         <p th:text="${success}"></p>                     </div>                     <form class="p-2" th:action="@{/create}" th:object="${employee}" method="post">                         <center>                             <h4 style="font-family: 'Times New Roman', Times, serif;">Add Employee</h4>                         </center>                          <div class="row p-2">                             <label class="p-1" for="employeeName">Employee Name</label>                             <input type="text" th:field="*{employeeName}" class="form-control"                                 placeholder="employee name" required>                         </div>                          <div class="row p-2">                             <label class="p-1" for="employeeEmail">Email</label>                             <input type="text" th:field="*{employeeEmail}" class="form-control"                                 placeholder="email address" required>                         </div>                          <div class="row p-2">                             <label class="p-1" for="employeePhone">Phone</label>                             <input type="tel" th:field="*{employeePhone}" class="form-control"                                 placeholder="phone number" required>                         </div>                          <div class="row p-2">                             <label class="p-1">Gender</label>                             <select th:field="*{employeeGender}" class="form-select" required>                                 <option value="" selected>select option</option>                                 <option value="Male">Male</option>                                 <option value="Female">Female</option>                             </select>                         </div>                          <div class="row p-2">                             <label class="p-1" for="employeeSalary">Phone</label>                             <input type="number" th:field="*{employeeSalary}" class="form-control" placeholder="salary"                                 required>                         </div>                          <div class="row p-2">                             <label class="p-1" for="employeeRole">Employee Role</label>                             <select th:field="*{employeeRole}" class="form-select" required>                                 <option value="" selected>select option</option>                                 <option value="Java">Java Developer</option>                                 <option value="Python">Python Developer</option>                                 <option value="Web">Web Developer</option>                                 <option value="Android">Android Developer</option>                                 <option value="UI">UI Developer</option>                             </select>                         </div>                          <button type="submit" class="btn btn-success mt-3 mb-2">Add Employee</button>                     </form>                 </div>              </div>         </div>     </div>     </div>       <!-- model for update-->     <div class="modal fade" id="exampleModalToggle2" aria-hidden="true" aria-labelledby="exampleModalToggleLabel"         tabindex="-1">         <div class="modal-dialog modal-dialog-centered">             <div class="modal-content">                 <div class="modal-body">                     <form class="p-2" th:action="@{/update}" th:object="${employee}" method="post">                         <!-- Check if errorMessage is present in the model and display it -->                         <div th:if="${errorMessage}" class="alert alert-danger" role="alert">                             <p th:text="${errorMessage}"></p>                         </div>                          <center>                             <h4 style="font-family: 'Times New Roman', Times, serif;">Update Employee</h4>                         </center>                          <div class="row p-1">                             <label class="p-1" for="id">Employee ID</label>                             <input type="text" th:field="*{id}" class="form-control" placeholder="employee id" required>                         </div>                          <div class="row p-1">                             <label class="p-1" for="employeeName">Employee Name</label>                             <input type="text" th:field="*{employeeName}" class="form-control"                                 placeholder="employee name" required>                         </div>                          <div class="row p-1">                             <label class="p-1" for="employeeEmail">Email</label>                             <input type="text" th:field="*{employeeEmail}" class="form-control"                                 placeholder="email address" required>                         </div>                          <div class="row p-1">                             <label class="p-1" for="employeePhone">Phone</label>                             <input type="tel" th:field="*{employeePhone}" class="form-control"                                 placeholder="phone number" required>                         </div>                          <div class="row p-1">                             <label class="p-1">Gender</label>                             <select th:field="*{employeeGender}" class="form-select" required>                                 <option value="" selected>select option</option>                                 <option value="Male">Male</option>                                 <option value="Female">Female</option>                             </select>                         </div>                          <div class="row p-1">                             <label class="p-1" for="employeeSalary">Phone</label>                             <input type="number" th:field="*{employeeSalary}" class="form-control" placeholder="salary"                                 required>                         </div>                          <div class="row p-1">                             <label class="p-1" for="employeeRole">Employee Role</label>                             <select th:field="*{employeeRole}" class="form-select" required>                                 <option value="" selected>select option</option>                                 <option value="Java">Java Developer</option>                                 <option value="Python">Python Developer</option>                                 <option value="Web">Web Developer</option>                                 <option value="Android">Android Developer</option>                                 <option value="UI">UI Developer</option>                             </select>                         </div>                          <button type="submit" class="btn btn-primary mt-3 mb-2">Update Employee</button>                     </form>                 </div>              </div>         </div>     </div>     </div>       <!-- model for delete-->     <div class="modal fade" id="exampleModalToggle3" aria-hidden="true" aria-labelledby="exampleModalToggleLabel"         tabindex="-1">         <div class="modal-dialog modal-dialog-centered">             <div class="modal-content">                 <div class="modal-body">                     <form class="p-2" th:action="@{/remove}" th:object="${employee}" method="post">                         <!-- Alert message -->                         <div th:if="${alertMessage}" class="alert alert-danger">                             <p th:text="${alertMessage}"></p>                         </div>                          <center>                             <h4 style="font-family: 'Times New Roman', Times, serif;">Delete Employee</h4>                         </center>                          <div class="row p-2">                             <label class="p-1" for="id">Employee ID</label>                             <input type="text" th:field="*{id}" class="form-control" placeholder="employee id" required>                         </div>                          <button type="submit" class="btn btn-danger mt-3 mb-2">Delete Employee</button>                     </form>                  </div>              </div>         </div>     </div>     </div>      <!-- Delete All employees-->     <div class="modal fade" id="deleteAllModal4" aria-hidden="true" aria-labelledby="deleteAllModalLabe4" tabindex="-1">         <div class="modal-dialog modal-dialog-centered">             <div class="modal-content">                 <div class="modal-body">                     <form class="p-2" th:action="@{/remove/all}" th:object="${confirmationForm}" method="post">                         <center>                             <h4 style="font-family: 'Times New Roman', Times, serif;">Delete All Employees</h4>                         </center>                          <div class="row p-2">                             <label class="p-3 text-warning" for="confirmation">Type 'Yes' For Confirmation</label>                             <input type="text" th:field="*{confirmation}" class="form-control"                                 placeholder="confirmation" required>                         </div>                          <button type="submit" class="btn btn-dark mt-3 mb-2">Delete All Employees</button>                     </form>                 </div>             </div>         </div>     </div>       <!-- bootstrap js -->     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script> </body>  </html> 

In above HTML code I attached Thymeleaf URL to HTML element. And the main thing is for every form in th:acton attribute I provide the Controller Handlers based on the Logic. Now The Thymeleaf Will take care of it.

Repository

In this Project I created one Mongo Repository for performing CRUD operations. @Repository is used for creating Mongo Repository. And it is possible to use all CRUD Operations by using java interface. This interface is extends to Mongo Repository.

Java
package com.ems.app.repo;  import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository;  import com.ems.app.pojo.Employee;  @Repository public interface EmployeeRepo extends MongoRepository<Employee, String>{  } 

In above code I created one interface that is EmployeeRepo which extends to MongoRepository. I used MongoDB that's why here I used Mongo Repository, For other databases It is different one more thing is the MongoRepository takes two arguments namely first one is name of the POJO class, for performing operation on It. The Second one is Datatype of the id in POJO class. In my Employee pojo I declared id as String datatype because the employee id contains both letters and digits. This EmployeeRepo interface is used for insert, delete, update, retrieve of data.

Controller Layer

The Controller layer is created by using @Controller annotation in Spring boot. The Controller class is used for processing the incoming API requests, And Preparing the Model and returning the view to be rendered as a response. In this Controller class I create entire project logic here. I will explain each and every thing in this layer by dividing them into small pieces.

EmployeeController.java

Java
package com.ems.app.controller;  import java.util.List; import java.util.Optional; import java.util.Random;  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.PostMapping;  import com.ems.app.pojo.ConfirmationForm; import com.ems.app.pojo.Employee; import com.ems.app.repo.EmployeeRepo;  @Controller public class EmployeeController {      @Autowired     private EmployeeRepo employeeRepo;      // display the html page     @GetMapping("/")     public String getIndex(Model model) {         List<Employee> employeeList = employeeRepo.findAll();         model.addAttribute("employees", employeeList);         model.addAttribute("employee", new Employee());         model.addAttribute("confirmationForm", new ConfirmationForm());         return "index";     }      // Insert employee data     @PostMapping("/create")     public String newEmployee(Employee employee, Model model) {         model.addAttribute("employee", new Employee());          // creating dynamic Employee ID         String empId = "EMP";         Random random = new Random();         long randomNumber = 1000 + random.nextInt(9000);         empId = empId + randomNumber;         employee.setId(empId);          // save the employee         employeeRepo.save(employee);          return "redirect:/";     }      // update the existing employee     @PostMapping("/update")     public String updateEmployee(@ModelAttribute Employee employee, Model model) {         model.addAttribute("employee", new Employee());         Optional<Employee> existingEmployee = employeeRepo.findById(employee.getId());          // checking employee exist or not         if (existingEmployee.isPresent()) {             employeeRepo.save(employee);         } else {             model.addAttribute("errorMessage", "Employee with ID " + employee.getId() + " not found.");         }         return "redirect:/";     }      // delete an employee by id     @PostMapping("/remove")     public String removeEmployee(Employee employee, Model model) {         model.addAttribute("employee", new Employee());         Optional<Employee> existingEmployee = employeeRepo.findById(employee.getId());         if (existingEmployee.isPresent()) {             employeeRepo.deleteById(employee.getId());         }         return "redirect:/";     }      // delete all employees data by confromation     @PostMapping("/remove/all")     public String removeAll(@ModelAttribute ConfirmationForm confirmationForm, Model model) {         String confirmation = confirmationForm.getConfirmation();         if ("Yes".equalsIgnoreCase(confirmation)) {             employeeRepo.deleteAll();         } else {             return "redirect:/";         }         return "redirect:/";     }  } 

In above code I implemented different handlers for different purposes. Here Handler means Request URL. In this I used more then 3 handlers below I listed those.

  • @GetMapping("/") this handler is used for display the html page
  • @PostMapping("/create") this handler is used for insert employee data
  • @PostMapping("/update") this handler is used for update an existing employee by using employee id
  • @PostMapping("/remove") this handler is used for delete an employee by using employee id
  • @PostMapping("/remove/all") this handler is used for delete all employees details by providing conformation

And also I used EmployeeRepo here for performing the back-end operations by using it's object.

Display HTML Page

For Displaying HTML page I used Thymeleaf for rendering purpose. For this I created one GET Handler which is used for GET Request which working as HTTP GET method.

Java
@GetMapping("/")     public String getIndex(Model model) {         List<Employee> employeeList = employeeRepo.findAll();         model.addAttribute("employees", employeeList);         model.addAttribute("employee", new Employee());         model.addAttribute("confirmationForm", new ConfirmationForm());         return "index";     } 

Output screen of Index Page:

Index Page for Employee Management System

In above piece of code I created one method which is type String. After that I passed Model class as argument to this method. This Model class is used for creating model attributes which are used for rendering the View in the HTML content. After that I create one list for gathering all employees data by using EmployeeRepo Object. In this Object I used findAll() which is used for get all employee data. After that Created one employees model attribute for employeeList. This employees model attribute is send to html page by using Model after that In HTML page the Thymeleaf hold this attribute and display the data in the form Table. And I created One more Model Attribute that is employee which is used for handling the employee pojo class from Thymeleaf Side. And finally I return the index page for this method.

Insert Employee Data

For Inserting Employee data into database I used EmployeeRepo object which provides save() methods which is used for saving employee data into database.

Java
@PostMapping("/create")     public String newEmployee(Employee employee, Model model) {         model.addAttribute("employee", new Employee());         // creating dynamic Employee ID         String empId = "EMP";         Random random = new Random();         long randomNumber = 1000 + random.nextInt(9000);         empId = empId + randomNumber;         employee.setId(empId);         // save the employee         employeeRepo.save(employee);         return "redirect:/";     } 

Output screen of Insert Employee:

Insert Employee in Database

Here I created A POST mapping because I this method I send data into database that's why I used post mapping here. As well as I created a model attribute for handling employee pojo in the HTML page using Thymeleaf. After I created a random Employee id by using Random class in Java. For Random ID, I take EMP as prefix of the Employee ID, After that dynamically generate 4 Digit number then con-cat both of them. After successfully generating Employee ID Set this value to id in Employee pojo class by using setId ()method. After that I save the employee data into database. In HTML page created one form for gathering employee data. After Successfully insert employee data that will displayed in the Table.

Update Employee Data

If you want to update an employee, you need existing employee ID then we can update employee data other wise not possible. It is a same Inserting data but Before inserting in this method I check if employee id exist or not. If exist I give Access to update employee information.

Java
@PostMapping("/update")     public String updateEmployee(@ModelAttribute Employee employee, Model model) {         model.addAttribute("employee", new Employee());         Optional<Employee> existingEmployee = employeeRepo.findById(employee.getId());          // checking employee exist or not         if (existingEmployee.isPresent()) {             employeeRepo.save(employee);         } else {             model.addAttribute("errorMessage", "Employee with ID " + employee.getId() + " not found.");         }         return "redirect:/";     } 


Output screen of Update Employee Details:

Updating Employee Information in System

After Successful Employee details update redirect to Index page and the is visible in the table. For I used Post Mapping means I Posting the data that's why I use this mapping. It is possible using Thymeleaf in HTML page.

Delete Employee Data

For Deleting an Employee, we need Employee ID, then only we can be able to delete an existing employee otherwise it's not possible to delete. After Successful delete, the result is updated in Employee table for this I used Thymeleaf for handling the Employee pojo class. For this used post mapping for comparing employee id with employee data.

Java
@PostMapping("/remove")     public String removeEmployee(Employee employee, Model model) {         model.addAttribute("employee", new Employee());         Optional<Employee> existingEmployee = employeeRepo.findById(employee.getId());         if (existingEmployee.isPresent()) {             employeeRepo.deleteById(employee.getId());         }         return "redirect:/";     } 

Output screen of Delete Employee:

Delete Employee from the Database

After Providing the An Employee ID click on the given button This button triggers the Thymeleaf. The Thymeleaf will perform operation on employee model attribute. This Employee Attribute is created on Controller class. In this Controller class Deletion operation performed using EmployeeRepo object after successfully deleting the employee this result is updated in Employee Table.

Delete All Employees

The Delete All employee's logic is working based on user conformation. The Conformation is nothing but while before deleting all data the application asks your conformation, if you type yes in the given text field means your conformed to delete all employee's data. From HTML page side the Thymeleaf is perform this by holding ConfirmationForm pojo. This ConfirmationForm is accepting a String. if That string is matches with yes then deleted all data automatically.

Java
@PostMapping("/remove/all")     public String removeAll(@ModelAttribute ConfirmationForm confirmationForm, Model model) {         String confirmation = confirmationForm.getConfirmation();         if ("Yes".equalsIgnoreCase(confirmation)) {             employeeRepo.deleteAll();         } else {             return "redirect:/";         }         return "redirect:/";     } 

Output Screen of Delete all Employees:

Delete All Employee Details


While click on Delete All button index page this form will open dynamically. If you enter Yes in that text field That means Your conformed delete all employees. After That Will be triggered on both HTML page and MongoDB also. After Delete All Employees the HTML page Look like below mentioned picture:

After Deleting All Employees



Next Article
Employee Management System Project using Spring Boot

E

eswarbe06sp
Improve
Article Tags :
  • Java
  • Geeks Premier League
  • Advance Java
  • Java-Spring-Boot
  • Java Projects
  • Geeks Premier League 2023
Practice Tags :
  • Java

Similar Reads

    Spring Boot - Project Deployment Using Tomcat
    Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because it’s a rapid production-ready envir
    5 min read
    Inventory Management System using Spring Boot
    Inventory Management System plays an important role in Business for tracking the Inventory, and It is used for tracking and movement of goods. In this article, we have provided some basic functionality for the Inventory Management System like an Analysis report of goods, adding new Products to the S
    15 min read
    Book Inventory System Using Spring Boot
    The Book Inventory System in Spring Boot plays an important role in Business logic. Mostly the online Book Inventory System is developed with the required business logic. Here we created a simple Spring Boot Application for the Book Inventory System, This application provides basic functionalities f
    15+ min read
    Spring Boot - Dependency Management
    Spring Boot framework is the most popular web development framework. No doubt, it provides an abundance of essential features and a convenient way to handle those features. At the heart of Spring Boot is the 'Dependency Management' feature. Importance of Dependency ManagementCentralized Dependency M
    6 min read
    Multi-Module Project With Spring Boot
    Multi-Module project with Spring Boot refers to a project structure where multiple modules or subprojects are organized under a single parent project. Each module can represent a distinct component, functionality, or layer of the application, allowing for better organization, maintainability, and co
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences