Easy CRUD Application Development with Spring Boot

Easy CRUD Application Development with Spring Boot

Building a Simple Employee Management System with Spring Boot and Thymeleaf

In this blog post, we will walk through the process of building a simple employee management system using Spring Boot and Thymeleaf. This application will allow users to add, update, delete, and list employee records. We will also use Spring Data JPA for database operations and Bootstrap for styling the web pages.

Prerequisites

Before we start, make sure you have the following installed on your machine:

  • Java 17 or higher

  • Maven 3.6.0 or higher

  • A relational database (e.g., MySQL)

Project Setup

  1. Create a new Spring Boot project: You can use Spring Initializr (https://start.spring.io/) to generate a new Spring Boot project with the following dependencies:

    • Spring Web

    • Spring Data JPA

    • Thymeleaf

    • MySQL Driver

  2. Clone the repository:

     git clone https://github.com/sudhirskp/thymeleafdemo.git
     cd thymeleafdemo
    
  3. Configure the database: Update the application.properties file in src/main/resources with your database connection details.

Project Structure

Here is an overview of the project structure:

  • src/main/java/skp/test/demo/ThymeleafdemoApplication.java: Main class for running the Spring Boot application.

  • src/main/java/skp/test/demo/controller/EmployeeController.java: Controller class for handling web requests.

  • src/main/java/skp/test/demo/entity/Employee.java: Entity class representing an employee.

  • src/main/java/skp/test/demo/service/EmployeeService.java: Service class for business logic related to employees.

  • src/main/java/skp/test/demo/dao/EmployeeRepository.java: Repository interface for database operations.

  • src/main/resources/templates/employees/employee-form.html: Thymeleaf template for the employee form.

  • src/main/resources/templates/employees/list-employees.html: Thymeleaf template for listing employees.

Implementing the Application

1. Main Application Class

The main class serves as the entry point for the Spring Boot application.

package skp.test.demo;

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

/**
 * The main class for the Thymeleafdemo Spring Boot application.
 * This class contains the main method which serves as the entry point for the Spring Boot application.
 */
@SpringBootApplication
public class ThymeleafdemoApplication {

    /**
     * The main method which serves as the entry point for the Spring Boot application.
     * It delegates to Spring Boot's SpringApplication class by calling run.
     *
     * @param args command-line arguments (none are used here)
     */
    public static void main(String[] args) {
        SpringApplication.run(ThymeleafdemoApplication.class, args);
    }
}

2. Entity Class

The Employee entity class represents an employee record in the database.

package skp.test.demo.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "employee")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    // Constructors, getters, and setters
    public Employee() {}

    public Employee(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public int getId() {
        return id;
    }

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

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }
}

3. Repository Interface

The EmployeeRepository interface extends JpaRepository to provide CRUD operations for the Employee entity.

package skp.test.demo.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import skp.test.demo.entity.Employee;

import java.util.List;

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
    public List<Employee> findAllByOrderByFirstNameAsc();
}

4. Service Class

The EmployeeService class contains the business logic for managing employees.

package skp.test.demo.service;

import skp.test.demo.entity.Employee;
import skp.test.demo.dao.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    public List<Employee> findAll() {
        return employeeRepository.findAllByOrderByFirstNameAsc();
    }

    public Employee findById(int id) {
        return employeeRepository.findById(id).orElse(null);
    }

    public void save(Employee employee) {
        employeeRepository.save(employee);
    }

    public void deleteById(int id) {
        employeeRepository.deleteById(id);
    }
}

5. Controller Class

The EmployeeController class handles web requests and interacts with the service layer.

package skp.test.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import skp.test.demo.entity.Employee;
import skp.test.demo.service.EmployeeService;

import java.util.List;

@Controller
@RequestMapping("/employees")
public class EmployeeController {

    private EmployeeService employeeService;

    @Autowired
    public EmployeeController(EmployeeService theEmployeeService) {
        employeeService = theEmployeeService;
    }

    @GetMapping("/list")
    public String listEmployees(Model theModel) {
        List<Employee> theEmployees = employeeService.findAll();
        theModel.addAttribute("employees", theEmployees);
        return "employees/list-employees";
    }

    @GetMapping("/showformforadd")
    public String addEmployee(Model theModel) {
        Employee theEmployee = new Employee();
        theModel.addAttribute("employee", theEmployee);
        return "employees/employee-form";
    }

    @GetMapping("/showformforupdate")
    public String showFormForUpdate(@RequestParam("employeeId") int theId, Model theModel) {
        Employee theEmployee = employeeService.findById(theId);
        theModel.addAttribute("employee", theEmployee);
        return "employees/employee-form";
    }

    @GetMapping("/delete")
    public String delete(@RequestParam("employeeId") int theId) {
        employeeService.deleteById(theId);
        return "redirect:/employees/list";
    }

    @PostMapping("/save")
    public String saveEmployee(@ModelAttribute("employee") Employee theEmployee) {
        employeeService.save(theEmployee);
        return "redirect:/employees/list";
    }
}

6. Thymeleaf Templates

The employee-form.html template is used to add and update employee details.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
    <title>Save Employee</title>
</head>
<body>
<div class="container">
    <h1>Enter Employee Details</h1>
    <hr>
    <form th:action="@{/employees/save}" th:object="${employee}" method="POST">
        <input type="hidden" th:field="*{id}">
        <input type="text" th:field="*{firstName}" class="form-control mb-4 w-25" placeholder="First name">
        <input type="text" th:field="*{lastName}" class="form-control mb-4 w-25" placeholder="Last name">
        <input type="text" th:field="*{email}" class="form-control mb-4 w-25" placeholder="Email">
        <button type="submit" class="btn btn-info col-2">Save</button>
    </form>
    <a th:href="@{/employees/list}">Back to Employee list</a>
</div>
</body>
</html>

The list-employees.html template is used to display the list of employees.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
    <title>Employee List</title>
</head>
<body>
<div class="container">
    <h1>Employee List</h1>
    <hr>
    <table class="table table-striped">
        <thead>
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="employee : ${employees}">
            <td th:text="${employee.firstName}">First Name</td>
            <td th:text="${employee.lastName}">Last Name</td>
            <td th:text="${employee.email}">Email</td>
            <td>
                <a th:href="@{/employees/showformforupdate(employeeId=${employee.id})}" class="btn btn-primary">Update</a>
                <a th:href="@{/employees/delete(employeeId=${employee.id})}" class="btn btn-danger">Delete</a>
            </td>
        </tr>
        </tbody>
    </table>
    <a th:href="@{/employees/showformforadd}" class="btn btn-success">Add Employee</a>
</div>
</body>
</html>

Running the Application

  1. Build the project:

     mvn clean install
    
  2. Run the application:

     mvn spring-boot:run
    
  3. Access the application: Open your browser and navigate to http://localhost:8080/employees/list to start managing employee records.

DataBase-MySql

Github : https://github.com/sudhirskp/springboot-crud-app

In this blog post, we guide you through creating a simple employee management system using Spring Boot and Thymeleaf. This application supports adding, updating, deleting, and listing employee records, utilizing Spring Data JPA for database interactions and Bootstrap for styling. We cover everything from setting up your project and configuring the database to implementing the application logic and creating user interfaces with Thymeleaf templates. Follow along to build and run your own employee management system effortlessly.