Spring Boot CRUD Tutorial for Freshers: Build an Employee API with MySQL Step by Step

Quick answer: A Spring Boot CRUD tutorial teaches you the four actions every application needs: Create, Read, Update and Delete. In this guide you will build an Employee REST API with Spring Boot, Spring Data JPA and MySQL, add validation and a global exception handler, and test every endpoint in Postman. You will use the standard layers (Controller, Service, Repository, Entity) that interviewers love to ask about. Follow the steps in order, type the code yourself and push the finished project to GitHub. This tutorial from VibrantMinds Technologies in Pune is written for freshers who want a real, explainable project.

It is for students and freshers who search for Spring Boot CRUD example, Spring Boot REST API with MySQL, how to connect Spring Boot to MySQL, Spring Data JPA CRUD, Spring Boot project for freshers or employee management project in Spring Boot.

Versions change over time. This tutorial follows common Spring Boot 3 practice (Java 17 or newer, jakarta packages). Check the official Spring documentation for the latest setup. No salary figures, statistics or job guarantees are given.

What You Will Build

An Employee API with these endpoints:

Action

HTTP method

Endpoint

What it does

Create

POST

/api/employees

Add a new employee

Read all

GET

/api/employees

List all employees

Read one

GET

/api/employees/{id}

Get one employee by id

Update

PUT

/api/employees/{id}

Change an employee's details

Delete

DELETE

/api/employees/{id}

Remove an employee

Request flow you will implement:

Postman → Controller → Service → Repository → MySQL → back to Postman

What You Need Before You Start

  • Java 17 or newer (JDK installed)

  • An IDE: IntelliJ IDEA, Eclipse or VS Code

  • MySQL installed and running, plus a client (MySQL Workbench or the command line)

  • Maven (comes with most IDEs)

  • Postman (to test the API)

  • Git (to push your project to GitHub)

Step 1: Create the MySQL Database

Open your MySQL client and run:

sql

CREATE DATABASE employee_db;
CREATE DATABASE employee_db;
CREATE DATABASE employee_db;

You do not need to create the table. Spring Data JPA can create it for us from the entity class (in development).

Step 2: Create the Spring Boot Project

Go to the official Spring Initializr website (start.spring.io) or use your IDE's Spring Initializr option. Choose:

  • Project: Maven

  • Language: Java

  • Spring Boot: a stable 3.x version

  • Group: com.example

  • Artifact: employee-api

  • Packaging: Jar

  • Java: 17 or newer

  • Dependencies: Spring Web, Spring Data JPA, MySQL Driver, Validation

Generate, download, unzip and open the project in your IDE.

Your pom.xml dependencies should include:

xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

Step 3: Configure the Database Connection

Open src/main/resources/application.properties and add:

properties

spring.datasource.url=jdbc:mysql://localhost:3306/employee_db
spring.datasource.username=root
spring.datasource.password=your_password_here

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.datasource.url=jdbc:mysql://localhost:3306/employee_db
spring.datasource.username=root
spring.datasource.password=your_password_here

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.datasource.url=jdbc:mysql://localhost:3306/employee_db
spring.datasource.username=root
spring.datasource.password=your_password_here

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

Important notes:

  • Replace root and your_password_here with your own MySQL username and password.

  • Never push real passwords to a public GitHub repository. Use environment variables or a separate local profile for real credentials.

  • ddl-auto=update is convenient for learning. In real projects, teams usually manage tables with migration tools and use stricter settings.

  • show-sql=true prints the SQL in your console so you can see what JPA does.

Step 4: Project Structure

Create these packages inside com.example.employeeapi:

com.example.employeeapi
├── controller      → EmployeeController
├── service         → EmployeeService
├── repository      → EmployeeRepository
├── entity          → Employee
└── exception       → ResourceNotFoundException, GlobalExceptionHandler
com.example.employeeapi
├── controller      → EmployeeController
├── service         → EmployeeService
├── repository      → EmployeeRepository
├── entity          → Employee
└── exception       → ResourceNotFoundException, GlobalExceptionHandler
com.example.employeeapi
├── controller      → EmployeeController
├── service         → EmployeeService
├── repository      → EmployeeRepository
├── entity          → Employee
└── exception       → ResourceNotFoundException, GlobalExceptionHandler

Each layer has one job. Keep them separate.

Step 5: Create the Entity (The Table in Java)

entity/Employee.java

java

package com.example.employeeapi.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Name is required")
    @Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters")
    @Column(nullable = false)
    private String name;

    @NotBlank(message = "Email is required")
    @Email(message = "Email must be valid")
    @Column(nullable = false, unique = true)
    private String email;

    @NotBlank(message = "Department is required")
    private String department;

    public Employee() {
    }

    public Employee(String name, String email, String department) {
        this.name = name;
        this.email = email;
        this.department = department;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

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

    public String getDepartment() { return department; }
    public void setDepartment(String department) { this.department = department; }
}
package com.example.employeeapi.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Name is required")
    @Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters")
    @Column(nullable = false)
    private String name;

    @NotBlank(message = "Email is required")
    @Email(message = "Email must be valid")
    @Column(nullable = false, unique = true)
    private String email;

    @NotBlank(message = "Department is required")
    private String department;

    public Employee() {
    }

    public Employee(String name, String email, String department) {
        this.name = name;
        this.email = email;
        this.department = department;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

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

    public String getDepartment() { return department; }
    public void setDepartment(String department) { this.department = department; }
}
package com.example.employeeapi.entity;

import jakarta.persistence.*;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;

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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Name is required")
    @Size(min = 2, max = 100, message = "Name must be between 2 and 100 characters")
    @Column(nullable = false)
    private String name;

    @NotBlank(message = "Email is required")
    @Email(message = "Email must be valid")
    @Column(nullable = false, unique = true)
    private String email;

    @NotBlank(message = "Department is required")
    private String department;

    public Employee() {
    }

    public Employee(String name, String email, String department) {
        this.name = name;
        this.email = email;
        this.department = department;
    }

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

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

    public String getDepartment() { return department; }
    public void setDepartment(String department) { this.department = department; }
}

What each annotation means:

Annotation

Meaning

@Entity

This class maps to a database table

@Table(name = "employees")

The table name

@Id

Primary key

@GeneratedValue(strategy = IDENTITY)

MySQL generates the id automatically

@NotBlank, @Email, @Size

Validation rules

@Column(unique = true)

No two employees can share an email

Step 6: Create the Repository (Talks to the Database)

repository/EmployeeRepository.java

java

package com.example.employeeapi.repository;

import com.example.employeeapi.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {

    boolean existsByEmail(String email);
}
package com.example.employeeapi.repository;

import com.example.employeeapi.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {

    boolean existsByEmail(String email);
}
package com.example.employeeapi.repository;

import com.example.employeeapi.entity.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {

    boolean existsByEmail(String email);
}

Why this is powerful: By extending JpaRepository, you get save, findAll, findById, deleteById and more without writing any SQL or implementation. existsByEmail is a derived query: Spring creates the query from the method name.

Step 7: Create a Custom Exception

exception/ResourceNotFoundException.java

java

package com.example.employeeapi.exception;

public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String message) {
        super(message);
    }
}
package com.example.employeeapi.exception;

public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String message) {
        super(message);
    }
}
package com.example.employeeapi.exception;

public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException(String message) {
        super(message);
    }
}

Step 8: Create the Service (Business Logic)

service/EmployeeService.java

java

package com.example.employeeapi.service;

import com.example.employeeapi.entity.Employee;
import com.example.employeeapi.exception.ResourceNotFoundException;
import com.example.employeeapi.repository.EmployeeRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {

    private final EmployeeRepository repository;

    public EmployeeService(EmployeeRepository repository) {
        this.repository = repository;
    }

    public Employee create(Employee employee) {
        if (repository.existsByEmail(employee.getEmail())) {
            throw new IllegalArgumentException("An employee with this email already exists");
        }
        return repository.save(employee);
    }

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

    public Employee findById(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Employee not found with id " + id));
    }

    public Employee update(Long id, Employee updated) {
        Employee existing = findById(id);
        existing.setName(updated.getName());
        existing.setEmail(updated.getEmail());
        existing.setDepartment(updated.getDepartment());
        return repository.save(existing);
    }

    public void delete(Long id) {
        Employee existing = findById(id);
        repository.delete(existing);
    }
}
package com.example.employeeapi.service;

import com.example.employeeapi.entity.Employee;
import com.example.employeeapi.exception.ResourceNotFoundException;
import com.example.employeeapi.repository.EmployeeRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {

    private final EmployeeRepository repository;

    public EmployeeService(EmployeeRepository repository) {
        this.repository = repository;
    }

    public Employee create(Employee employee) {
        if (repository.existsByEmail(employee.getEmail())) {
            throw new IllegalArgumentException("An employee with this email already exists");
        }
        return repository.save(employee);
    }

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

    public Employee findById(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Employee not found with id " + id));
    }

    public Employee update(Long id, Employee updated) {
        Employee existing = findById(id);
        existing.setName(updated.getName());
        existing.setEmail(updated.getEmail());
        existing.setDepartment(updated.getDepartment());
        return repository.save(existing);
    }

    public void delete(Long id) {
        Employee existing = findById(id);
        repository.delete(existing);
    }
}
package com.example.employeeapi.service;

import com.example.employeeapi.entity.Employee;
import com.example.employeeapi.exception.ResourceNotFoundException;
import com.example.employeeapi.repository.EmployeeRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeService {

    private final EmployeeRepository repository;

    public EmployeeService(EmployeeRepository repository) {
        this.repository = repository;
    }

    public Employee create(Employee employee) {
        if (repository.existsByEmail(employee.getEmail())) {
            throw new IllegalArgumentException("An employee with this email already exists");
        }
        return repository.save(employee);
    }

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

    public Employee findById(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Employee not found with id " + id));
    }

    public Employee update(Long id, Employee updated) {
        Employee existing = findById(id);
        existing.setName(updated.getName());
        existing.setEmail(updated.getEmail());
        existing.setDepartment(updated.getDepartment());
        return repository.save(existing);
    }

    public void delete(Long id) {
        Employee existing = findById(id);
        repository.delete(existing);
    }
}

Notice: The service holds the business rules (duplicate email check, "not found" handling). It does not know anything about HTTP.

Step 9: Create the Controller (Handles HTTP)

controller/EmployeeController.java

java

package com.example.employeeapi.controller;

import com.example.employeeapi.entity.Employee;
import com.example.employeeapi.service.EmployeeService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    private final EmployeeService service;

    public EmployeeController(EmployeeService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<Employee> create(@Valid @RequestBody Employee employee) {
        Employee saved = service.create(employee);
        return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    }

    @GetMapping
    public List<Employee> getAll() {
        return service.findAll();
    }

    @GetMapping("/{id}")
    public Employee getById(@PathVariable Long id) {
        return service.findById(id);
    }

    @PutMapping("/{id}")
    public Employee update(@PathVariable Long id, @Valid @RequestBody Employee employee) {
        return service.update(id, employee);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        service.delete(id);
        return ResponseEntity.noContent().build();
    }
}
package com.example.employeeapi.controller;

import com.example.employeeapi.entity.Employee;
import com.example.employeeapi.service.EmployeeService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    private final EmployeeService service;

    public EmployeeController(EmployeeService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<Employee> create(@Valid @RequestBody Employee employee) {
        Employee saved = service.create(employee);
        return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    }

    @GetMapping
    public List<Employee> getAll() {
        return service.findAll();
    }

    @GetMapping("/{id}")
    public Employee getById(@PathVariable Long id) {
        return service.findById(id);
    }

    @PutMapping("/{id}")
    public Employee update(@PathVariable Long id, @Valid @RequestBody Employee employee) {
        return service.update(id, employee);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        service.delete(id);
        return ResponseEntity.noContent().build();
    }
}
package com.example.employeeapi.controller;

import com.example.employeeapi.entity.Employee;
import com.example.employeeapi.service.EmployeeService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    private final EmployeeService service;

    public EmployeeController(EmployeeService service) {
        this.service = service;
    }

    @PostMapping
    public ResponseEntity<Employee> create(@Valid @RequestBody Employee employee) {
        Employee saved = service.create(employee);
        return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    }

    @GetMapping
    public List<Employee> getAll() {
        return service.findAll();
    }

    @GetMapping("/{id}")
    public Employee getById(@PathVariable Long id) {
        return service.findById(id);
    }

    @PutMapping("/{id}")
    public Employee update(@PathVariable Long id, @Valid @RequestBody Employee employee) {
        return service.update(id, employee);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        service.delete(id);
        return ResponseEntity.noContent().build();
    }
}

Key annotations explained:

Annotation

Meaning

@RestController

Class handles HTTP requests and returns data (JSON)

@RequestMapping("/api/employees")

Base URL for all endpoints in this class

@PostMapping, @GetMapping, @PutMapping, @DeleteMapping

Map HTTP methods to Java methods

@RequestBody

Converts the JSON body into a Java object

@Valid

Runs the validation rules on that object

@PathVariable

Reads the {id} from the URL

Step 10: Add a Global Exception Handler (Clean Error Messages)

Without this, errors look confusing. With it, your API returns clear, consistent messages.

exception/GlobalExceptionHandler.java

java

package com.example.employeeapi.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<Map<String, Object>> handleNotFound(ResourceNotFoundException ex) {
        return build(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleBadRequest(IllegalArgumentException ex) {
        return build(HttpStatus.BAD_REQUEST, ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidation(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors()
                .forEach(error -> errors.put(error.getField(), error.getDefaultMessage()));

        Map<String, Object> body = new HashMap<>();
        body.put("timestamp", LocalDateTime.now().toString());
        body.put("status", HttpStatus.BAD_REQUEST.value());
        body.put("errors", errors);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
    }

    private ResponseEntity<Map<String, Object>> build(HttpStatus status, String message) {
        Map<String, Object> body = new HashMap<>();
        body.put("timestamp", LocalDateTime.now().toString());
        body.put("status", status.value());
        body.put("message", message);
        return ResponseEntity.status(status).body(body);
    }
}
package com.example.employeeapi.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<Map<String, Object>> handleNotFound(ResourceNotFoundException ex) {
        return build(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleBadRequest(IllegalArgumentException ex) {
        return build(HttpStatus.BAD_REQUEST, ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidation(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors()
                .forEach(error -> errors.put(error.getField(), error.getDefaultMessage()));

        Map<String, Object> body = new HashMap<>();
        body.put("timestamp", LocalDateTime.now().toString());
        body.put("status", HttpStatus.BAD_REQUEST.value());
        body.put("errors", errors);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
    }

    private ResponseEntity<Map<String, Object>> build(HttpStatus status, String message) {
        Map<String, Object> body = new HashMap<>();
        body.put("timestamp", LocalDateTime.now().toString());
        body.put("status", status.value());
        body.put("message", message);
        return ResponseEntity.status(status).body(body);
    }
}
package com.example.employeeapi.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<Map<String, Object>> handleNotFound(ResourceNotFoundException ex) {
        return build(HttpStatus.NOT_FOUND, ex.getMessage());
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleBadRequest(IllegalArgumentException ex) {
        return build(HttpStatus.BAD_REQUEST, ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidation(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors()
                .forEach(error -> errors.put(error.getField(), error.getDefaultMessage()));

        Map<String, Object> body = new HashMap<>();
        body.put("timestamp", LocalDateTime.now().toString());
        body.put("status", HttpStatus.BAD_REQUEST.value());
        body.put("errors", errors);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(body);
    }

    private ResponseEntity<Map<String, Object>> build(HttpStatus status, String message) {
        Map<String, Object> body = new HashMap<>();
        body.put("timestamp", LocalDateTime.now().toString());
        body.put("status", status.value());
        body.put("message", message);
        return ResponseEntity.status(status).body(body);
    }
}

What this gives you:

Situation

Status code

Message

Employee id does not exist

404 Not Found

"Employee not found with id 99"

Duplicate email

400 Bad Request

"An employee with this email already exists"

Missing or invalid field

400 Bad Request

A list of field errors

Step 11: Run the Application

Run the main class (EmployeeApiApplication) from your IDE, or use:

bash

mvn spring-boot:run
mvn spring-boot:run
mvn spring-boot:run

If everything is correct, the console shows that the application started on port 8080, and Hibernate creates the employees table. Check in MySQL:

sql

USE employee_db;
SHOW TABLES;
DESCRIBE employees;
USE employee_db;
SHOW TABLES;
DESCRIBE employees;
USE employee_db;
SHOW TABLES;
DESCRIBE employees;

Step 12: Test Every Endpoint in Postman

Test 1: Create an employee (POST)

  • URL: http://localhost:8080/api/employees

  • Body (raw, JSON):

json

{
  "name": "Asha Patil",
  "email": "asha@example.com",
  "department": "Engineering"
}
{
  "name": "Asha Patil",
  "email": "asha@example.com",
  "department": "Engineering"
}
{
  "name": "Asha Patil",
  "email": "asha@example.com",
  "department": "Engineering"
}

Expected: Status 201 Created and the saved employee with an id.

Test 2: Get all employees (GET)

  • URL: http://localhost:8080/api/employees

  • Expected: 200 OK and a JSON list.

Test 3: Get one employee (GET)

  • URL: http://localhost:8080/api/employees/1

  • Expected: 200 OK with that employee.

Test 4: Update an employee (PUT)

  • URL: http://localhost:8080/api/employees/1

  • Body:

json

{
  "name": "Asha Patil",
  "email": "asha@example.com",
  "department": "Product"
}
{
  "name": "Asha Patil",
  "email": "asha@example.com",
  "department": "Product"
}
{
  "name": "Asha Patil",
  "email": "asha@example.com",
  "department": "Product"
}

Expected: 200 OK with the updated department.

Test 5: Delete an employee (DELETE)

  • URL: http://localhost:8080/api/employees/1

  • Expected: 204 No Content.

Negative tests (very important for interviews):

Test

What to send

Expected

Missing name

{"name": "", "email": "a@b.com", "department": "HR"}

400 with "Name is required"

Invalid email

{"name": "Ravi", "email": "notanemail", "department": "HR"}

400 with "Email must be valid"

Duplicate email

Create the same email twice

400 with the duplicate message

Unknown id

GET /api/employees/9999

404 with "Employee not found"

Step 13: Understand What Happened (The Request Flow)

When you send POST /api/employees:

  1. Controller receives the request and converts the JSON into an Employee object (@RequestBody).

  2. Validation runs because of @Valid. If a rule fails, the exception handler returns 400.

  3. Service checks business rules, such as duplicate email.

  4. Repository calls save(), and Hibernate runs an INSERT in MySQL.

  5. The saved object returns up through the layers.

  6. The controller sends 201 Created with JSON.

Practise saying this flow aloud. It is one of the most common fresher interview questions.

Common Errors and How to Fix Them

Error you see

Likely cause

Fix

Communications link failure

MySQL is not running or the URL or port is wrong

Start MySQL and check spring.datasource.url

Access denied for user

Wrong username or password

Correct them in application.properties

Unknown database 'employee_db'

The database was not created

Run CREATE DATABASE employee_db;

Table 'employees' doesn't exist

ddl-auto setting is missing

Set spring.jpa.hibernate.ddl-auto=update while learning

Port 8080 was already in use

Another app uses the port

Stop it, or set server.port=8081

HTTP 415 Unsupported Media Type

Missing JSON header in Postman

Set body to raw JSON and Content-Type: application/json

HTTP 400 on a valid body

A validation rule failed

Read the error message in the response

Fields are null after save

Missing getters and setters or wrong JSON names

Add getters and setters and match field names

NoSuchBeanDefinitionException

Class is outside the main package or missing an annotation

Keep packages under com.example.employeeapi and add @Service or @Repository

jakarta import errors

Mixing old javax imports with Spring Boot 3

Use jakarta.* imports in Spring Boot 3

Improve the Project: Next Steps That Impress Interviewers

Upgrade

Why it helps

DTOs (separate request and response classes)

Do not expose entities directly. Cleaner and safer.

Pagination and sorting

Use Pageable with findAll(Pageable) for large lists

Search endpoint

Add findByDepartment or findByNameContaining in the repository

Unit tests

JUnit and Mockito tests for the service layer

Integration tests

@SpringBootTest with a test database

Logging

Use SLF4J logging in the service layer

Swagger / OpenAPI

Auto-generated API documentation

Security

Add Spring Security with login and roles

Docker

Run the API and MySQL with Docker Compose

A simple front end

HTML, CSS and JavaScript page that calls your API

Pick two or three and add them one by one. Each upgrade is a new talking point.

Put It on GitHub and Your Resume

  1. Create a .gitignore (Spring Initializr creates one) so target/ is not uploaded.

  2. Remove real passwords from application.properties before pushing.

  3. Write a README with: project goal, tech stack, setup steps, endpoint list, sample requests and screenshots of Postman tests.

  4. Make small, clear commits.

  5. Add the link to your resume.

Resume line example (use only what is true):

Built an Employee Management REST API using Spring Boot, Spring Data JPA and MySQL with validation, global exception handling and Postman-tested CRUD endpoints. (GitHub link)

Interview Questions on This Project

Q1. Explain the layers of your project.
Controller handles HTTP requests, service holds business rules, repository talks to the database, and the entity maps to a table.

Q2. What does @RestController do?
It combines @Controller and @ResponseBody, so methods return data (usually JSON) instead of views.

Q3. What is JpaRepository?
A Spring Data interface that provides ready-made CRUD methods like save, findAll, findById and deleteById without writing implementations.

Q4. What is the difference between @Controller and @RestController?
@Controller is typically used for returning views, while @RestController returns data directly in the response body.

Q5. What do @Valid and @NotBlank do?
@Valid triggers validation on the request object, and @NotBlank makes sure a text field is not null or empty.

Q6. Why use a global exception handler?
To return clear, consistent error responses and avoid repeating try and catch blocks in every controller method.

Q7. What is the difference between PUT and PATCH?
PUT usually replaces the whole resource, while PATCH updates only some fields.

Q8. What does ddl-auto=update do, and is it safe for production?
It updates the database schema from the entities. It is convenient while learning, but teams usually use migration tools and stricter settings in production.

Q9. Why should you not expose entities directly in APIs?
It can leak internal structure and cause tight coupling. DTOs give you control over what is sent and received.

Q10. How would you add pagination?
Use Pageable in the controller, call repository.findAll(pageable) and return a Page of results.

How VibrantMinds Technologies Helps You Build Real Projects

VibrantMinds Technologies Pvt. Ltd. is a Pune-based company that provides Java Full Stack training and placement support for freshers. If you searched for VibrantMinds or VibrantMinds Technologies, here is what that means:

  • Java Full Stack training (about 4 to 6 months): Core Java, Advanced Java, Java 8, SQL, Hibernate, Spring, Spring Boot, REST APIs, HTML, CSS and JavaScript, with data structures practice, projects, aptitude and communication training, group discussion and interview preparation. Please check the candidate portal for the latest syllabus and tools.

  • Project practice and feedback, so you build applications like this one and can explain every layer.

  • Mock interviews and aptitude practice to find your gaps before a real interview does.

  • Placement support: screening and assessment, drive coordination and interview support. Current openings are listed at https://candidates.vibrantminds.in/

VibrantMinds works as a talent ecosystem connecting candidates, colleges and hiring companies, with 1900+ partner colleges and 600+ hiring companies. Its placement support process runs in six steps: Requirement Mapping, Candidate Sourcing, Screening and Assessment, Drive Coordination, Interview Support and Onboarding Follow-up.

Past students have gone on to roles at companies such as Aress Software and Education Technologies, Saama Technologies and Three M Software. Results vary by candidate, skill level, effort and market conditions. VibrantMinds offers placement support, not a guaranteed job, and no legitimate recruiter should ask you to pay to be interviewed. Fees, syllabus and batch dates are on https://candidates.vibrantminds.in/ and should be confirmed directly before enrolling.

More fresher job guidance: https://candidates.vibrantminds.in/blog/fresher-jobs-pune-2026

Join Free VibrantMinds WhatsApp Groups for Fresher IT Job Updates

Looking for free WhatsApp groups, free IT job WhatsApp groups, a Java WhatsApp group for freshers or a job updates WhatsApp group in India? The VibrantMinds groups share fresher IT openings, campus and off-campus drives, walk-in interview alerts and interview preparation updates, free of charge, and they are open to freshers from every college. Join whichever group has space:

Never pay to apply. Legitimate recruiters do not charge candidates for tests, interviews or offer letters. Do not share OTPs, bank details or ID numbers with anyone you have not verified.

Frequently Asked Questions

1. How do I build a CRUD REST API in Spring Boot with MySQL?
Create a Spring Boot project with Spring Web, Spring Data JPA, MySQL Driver and Validation. Configure the database in application.properties, create an entity, a JpaRepository interface, a service class and a @RestController with POST, GET, PUT and DELETE methods. Add validation and a global exception handler, then test each endpoint in Postman.

2. How do I connect Spring Boot to MySQL?
Add the MySQL driver dependency, create a database, and set spring.datasource.url, spring.datasource.username and spring.datasource.password in application.properties. Make sure MySQL is running. Use spring.jpa.hibernate.ddl-auto=update while learning so tables are created from your entities.

3. What are the layers of a Spring Boot application?
Controller (handles HTTP requests and responses), service (business logic), repository (database access with Spring Data JPA) and entity (a Java class mapped to a table). Keeping layers separate makes code easier to test and change.

4. Why is my Spring Boot MySQL connection failing?
Common causes are MySQL not running, a wrong URL or port, a wrong username or password, or a missing database. Check the error message, confirm you can log in with the same credentials in MySQL Workbench or the command line and then update application.properties.

5. Is there a free WhatsApp group for IT freshers in Pune?
Yes. VibrantMinds runs free fresher IT job WhatsApp groups that share openings, drives and walk-in alerts. Join through the links in this article, verify every post and never pay to apply.

Conclusion: One Working CRUD Project Is a Strong Start

You have now built a complete Spring Boot CRUD application with MySQL: an entity, repository, service, controller, validation, a global exception handler and a full set of Postman tests. Practise explaining the request flow aloud, add two or three upgrades such as DTOs, pagination and unit tests, push the project to GitHub with a clear README and put it on your resume honestly. A project you can build from scratch and explain clearly improves your chances in interviews, though no one can promise a particular result.

If you are in Pune and want Java Full Stack training with project practice, interview preparation and placement support, VibrantMinds Technologies is here to help.

Contact VibrantMinds Technologies Pvt. Ltd.

Office Address

Viva Academy Building, Near St. Mary's Church & Petrol Pump Mumbai-Bangalore Highway, Warje, near to Karvenagar, Pune, Maharashtra 411058

Phone Number

+91 95035 79517

© 2025 VibrantMinds Technologies Pvt. Ltd All Right Reserved

Office Address

Viva Academy Building, Near St. Mary's Church & Petrol Pump Mumbai-Bangalore Highway, Warje, near to Karvenagar, Pune, Maharashtra 411058

Phone Number

+91 95035 79517

© 2025 VibrantMinds Technologies Pvt. Ltd All Right Reserved

Office Address

Viva Academy Building, Near St. Mary's Church & Petrol Pump Mumbai-Bangalore Highway, Warje, near to Karvenagar, Pune, Maharashtra 411058

Phone Number

+91 95035 79517

© 2025 VibrantMinds Technologies Pvt. Ltd All Right Reserved