Search Tutorials


Spring Boot 3 + MySQL CRUD Example | JavaInUse

Spring Boot 3 + MySQL CRUD Example

In this tutorial we will be creating a spring boot application to perform CRUD operations using MySQL database.
The spring boot project we will be developing is as follows -
Spring Boot 3 + MySQL CRUD Example

Video

This tutorial is explained in the below Youtube Video.

Implementation

We will be making use of Spring Initializr to create a spring boot project as follows -
Spring Boot 3 CRUD MySQL Initializr
In the pom.xml we have the spring-boot-starter-data-jpa dependency. This is used in a Spring Boot project to include the necessary dependencies to work with Java Persistence API (JPA) for data access and database operations. This dependency includes various libraries and components such as Hibernate, which is a popular implementation of the JPA specification. It provides abstractions and functionalities that make it easier to interact with relational databases. By including this dependency in a Spring Boot project, you can leverage JPA's features, such as entity mapping, database query support, and transaction management, to simplify the development of data-driven applications.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.2.2</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javainuse</groupId>
	<artifactId>boot-crud</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>boot-crud</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>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>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
Next in the application.properties file add the following MySQL configuration.
  • spring.datasource.url: Specifies the JDBC URL of the MySQL database connection. In our case, it will connect to a database named "javainusedb" on the localhost. The createDatabaseIfNotExist=true parameter ensures that if the database does not exist, it will be created. The useSSL=false parameter disables SSL encryption for the connection.
  • spring.datasource.username: Specifies the username to use for authentication when connecting to the MySQL database. In our case, the username is set to "root".
  • spring.datasource.password: Specifies the password to use for authentication when connecting to the MySQL
spring.datasource.url= jdbc:mysql://localhost/javainusedb?createDatabaseIfNotExist=true&useSSL=false
spring.datasource.username= root
spring.datasource.password= root

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto= update
If we now start the spring boot appplication, it does so successfully and connects to MySQL database and a database named javainusedb gets created.
Spring Boot 3 + MySQL Example
If we now go to mysql database-
Spring Boot 3 + MySQL Create
Next we create an entity class named Employee. This is the class which will map the employee to the MySQL table named employees.
package com.javainuse.bootmysqlcrud.entity;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

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

	public Employee(Long id, String name, String department) {
		super();
		this.id = id;
		this.name = name;
		this.department = department;
	}

	public Employee() {
	}

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

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

	@Column(name = "department")
	private String 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 getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}
}
In this class we make use of following annotations.
  • @Entity: This annotation is used to mark the class as a persistent entity, which means it can be stored and retrieved from a database.
  • @Table(name = "employees"): This annotation specifies the table name in the database that corresponds to this entity. In this case, the table name is "employees".
  • @Id: This annotation is used to mark the primary key field of the entity. In this case, the "id" field is the primary key.
  • @GeneratedValue(strategy = GenerationType.IDENTITY): This annotation specifies the generation strategy for the primary key value. In this case, the primary key value is generated by the database using the "IDENTITY" strategy. This strategy indicates that the primary key value is generated by the underlying database. It typically uses an auto-increment column in the database to generate unique primary key values.
  • @Column(name = "name"): This annotation is used to specify the column name in the database that corresponds to the "name" field.
  • @Column(name = "department"): This annotation is used to specify the column name in the database that corresponds to the "department" field.
Also previously in the application.properties file we have configured the following JPA properties-
  • spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect: This property specifies the Hibernate dialect to be used for communicating with the MySQL database. In this case, it is set to "org.hibernate.dialect.MySQLDialect", indicating that the MySQL database will be used.
  • spring.jpa.hibernate.ddl-auto=update: This property determines how Hibernate handles the database schema during application startup. The value "update" indicates that Hibernate should try to update the database schema based on the entities defined in your application. It will compare the database schema with the mapping information and apply any necessary changes to synchronize them. If for example we set this property to "none" then Hibernate will not be able to make any db schema changes.
If we now start the spring boot application and check the MySQL database we can see that a table named employee has been created in the mysql database.
Spring Boot + MySQL create table




Next we create a repository named EmployeeRepository. This is an interface which extends the JpaRepository. The JpaRepository in turn extends the CrudRepository interface.
The EmployeeRepository interface is specifically designed to interact with the database and perform CRUD operations (Create, Read, Update, Delete) on the Employee entity.
The generic parameters <Employee, Long> indicate that the repository will be dealing with objects of type Employee and their unique identifier will be of type Long.
package com.javainuse.bootmysqlcrud.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import com.javainuse.bootmysqlcrud.entity.Employee;

public interface EmployeeRepository extends JpaRepository<Employee, Long> {

}
When we extend the JpaRepository interface in our EmployeeRepository interface, Spring Data JPA automatically creates an instance of SimpleJpaRepository and assigns it to the EmployeeRepository bean at runtime. This means that when we use the EmployeeRepository interface in our code, the methods defined in the JpaRepository interface (including the ones inherited from CrudRepository and PagingAndSortingRepository) will be implemented by the SimpleJpaRepository class.

Create Employee API


Spring Boot + MySQL Create Operation

Employee DTO (Data Transfer Object)

Using DTO classes allows for a clear separation between the presentation layer and the domain layer. DTOs provide a way to transfer data between different layers, such as the controller and service layers, without leaking unnecessary information or domain-specific logic.
Create the EmployeeDto class as follows-
package com.javainuse.bootmysqlcrud.dto;

public class EmployeeDto {

	private Long id;
	private String name;
	private String department;

	public EmployeeDto(Long id, String name, String department) {
		super();
		this.id = id;
		this.name = name;
		this.department = department;
	}

	public EmployeeDto() {

	}

	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 getDepartment() {
		return department;
	}

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

Employee Mapper Implementation

In the service layer we need to convert EmployeeDto instance to Employee instance and viceversa. We perform this conversion operation using Employee Mapper.
package com.javainuse.bootmysqlcrud.mapper;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.entity.Employee;

public class EmployeeMapper {

	public static EmployeeDto mapToEmployeeDto(Employee employee) {
		return new EmployeeDto(employee.getId(), employee.getName(), employee.getDepartment());
	}

	public static Employee mapToEmployee(EmployeeDto employeeDto) {
		return new Employee(employeeDto.getId(), employeeDto.getName(), employeeDto.getDepartment());
	}

}

Service Implementation

We will now create the service layer. First let us create an interface named EmployeeService with single method named createEmployee which will create a new employee record. We are creating the service interface first as we want to follow the programming to an interface design principle.
package com.javainuse.bootmysqlcrud.service;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;

public interface EmployeeService {
	EmployeeDto createEmployee(EmployeeDto employeeDto);	
}
Next we implement the service implementation named EmployeeSericeImpl. This class we autowire the repository. There is a method called createEmployee which takes an EmployeeDto object as a parameter. Inside this method, it maps the EmployeeDto object to an Employee object using a class called EmployeeMapper. Then, we save the employee object to the database using the employeeRepository.save() method. Finally, we map the created employee object back to an EmployeeDto object using EmployeeMapper and return it.
package com.javainuse.bootmysqlcrud.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.javainuse.bootmysqlcrud.mapper.EmployeeMapper;
import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.entity.Employee;
import com.javainuse.bootmysqlcrud.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

	@Autowired
	private EmployeeRepository employeeRepository;

	@Override
	public EmployeeDto createEmployee(EmployeeDto employeeDto) {
		Employee employee = EmployeeMapper.mapToEmployee(employeeDto);
		Employee createdEmployee = employeeRepository.save(employee);
		return EmployeeMapper.mapToEmployeeDto(createdEmployee);
	}
}

Controller Implementation

EmployeeController class is a REST controller class that handles HTTP requests related to employee operations. It uses Spring's @RestController annotation to indicate that the class is a REST controller that facilitates the mapping of requests to methods.
The class has a dependency on the EmployeeService class, which is injected using the @Autowired annotation. This allows the class to utilize the methods provided by the EmployeeService to perform employee-related operations.
The class contains a single method, createEmployee, which is mapped to a POST request with the endpoint /employee. This method takes in an EmployeeDto object as the request body, representing the employee data to be created. It invokes the createEmployee method from the injected EmployeeService, passing the employeeDto as an argument. The response from the service method call is then wrapped in a ResponseEntity object, specifying the created employee DTO and the HTTP status code HttpStatus.CREATED as the response.
package com.javainuse.bootmysqlcrud.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.service.EmployeeService;

@RestController
public class EmployeeController {	

	@Autowired
	private EmployeeService employeeService;

	@PostMapping(value = "/employee")
	public ResponseEntity<EmployeeDto> createEmployee(@RequestBody EmployeeDto employeeDto) {
		EmployeeDto createdEmployee = employeeService.createEmployee(employeeDto);
		return new ResponseEntity<>(createdEmployee, HttpStatus.CREATED);
	}	
}

Test

Let us now test the create employee API.
Spring Boot + MySQL create employee API
If we check the MySQL database
Spring Boot + MySQL create record

Get Employee By Id API


Spring Boot + MySQL Get by Id Operation

Service Implementation

Create an exception named EmployeeNotFoundException which will be thrown if the employee with the specified id is not found.
package com.javainuse.bootmysqlcrud.exception;

public class EmployeeNotFoundException extends Exception {

	private static final long serialVersionUID = 1L;

	public EmployeeNotFoundException() {
	}

	public EmployeeNotFoundException(String message) {
		super(message);
	}
}
In the EmployeeService interface, the following method has been added - EmployeeDto getEmployeeById(Long employeeId) throws EmployeeNotFoundException.
This method is used to retrieve information about an employee based on their unique identifier, which is provided as the employeeId parameter. The method returns an EmployeeDto object, which is a DTO (Data Transfer Object) containing the details of the employee. Additionally, this method throws an EmployeeNotFoundException if no employee with the provided ID is found. This exception is used to handle cases where the requested employee does not exist in the system or cannot be found. By throwing this exception, the calling code can handle and respond to such errors appropriately.
package com.javainuse.bootmysqlcrud.service;

import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
import com.javainuse.bootmysqlcrud.dto.EmployeeDto;

public interface EmployeeService {
	EmployeeDto createEmployee(EmployeeDto employeeDto);	
	EmployeeDto getEmployeeById(Long employeeId) throws EmployeeNotFoundException;
}
Next in the EmployeeServiceImpl we implement the getEmployeeById method of the EmployeeService interface. This method takes an employeeId as a parameter and returns an EmployeeDto object, which represents a Data Transfer Object (DTO) carrying employee information.
The method starts by using the employeeRepository, which is an instance of a Spring Data JPA repository, to retrieve an employee record from the database using the employeeId. The findById method returns an Optional<Employee> instance which may contain the employee object if it exists.
Next, the code checks if the employee object is empty or not using the isEmpty() method. If it is empty, it means no employee record was found with the given employeeId. In such a case, the code throws an EmployeeNotFoundException which is a custom exception class. The exception message includes the employeeId that was not found.
If the employee object is not empty, it means a valid employee record exists with the given employeeId. To convert the Employee object to an EmployeeDto object, the code uses a EmployeeMapper class that provides a static method called mapToEmployeeDto. The mapToEmployeeDto method takes an Employee object as input and returns an EmployeeDto object.
Finally, the method returns the Employee Dto object representing the employee found in the database.
package com.javainuse.bootmysqlcrud.service;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
import com.javainuse.bootmysqlcrud.mapper.EmployeeMapper;
import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.entity.Employee;
import com.javainuse.bootmysqlcrud.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

	@Autowired
	private EmployeeRepository employeeRepository;

	@Override
	public EmployeeDto createEmployee(EmployeeDto employeeDto) {
		Employee employee = EmployeeMapper.mapToEmployee(employeeDto);
		Employee createdEmployee = employeeRepository.save(employee);
		return EmployeeMapper.mapToEmployeeDto(createdEmployee);
	}

	@Override
	public EmployeeDto getEmployeeById(Long employeeId) throws EmployeeNotFoundException {
		Optional<Employee> employee = employeeRepository.findById(employeeId);
		if (employee.isEmpty()) {
			throw new EmployeeNotFoundException("Employee with id - " + employeeId + " not found.");
		}
		return EmployeeMapper.mapToEmployeeDto(employee.get());
	}
}

Controller Implementation

Next in the controller class we define a GET request method that retrieves details of an employee by their employee ID. The @GetMapping annotation specifies that this method should handle HTTP GET requests with the specified URL "/employee/{employeeId}". The employeeId is a path variable and is extracted from the URL using the @PathVariable annotation. The method throws an EmployeeNotFoundException if the employee with the given ID is not found. Inside the method, it delegates the responsibility of retrieving the employee details to the employeeService which is an instance of the EmployeeService class. It calls the getEmployeeById method of the employeeService by passing the employeeId as a parameter. The result, which is an instance of EmployeeDto, is then returned as the response with a status code of OK (200) using the ResponseEntity class. If the requested employee is not found, it catches the EmployeeNotFoundException and re-throws it, allowing the exception to be handled by any exception handler defined in the application.
package com.javainuse.bootmysqlcrud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.service.EmployeeService;

@RestController
public class EmployeeController {

	private List<EmployeeDto> employees;

	@Autowired
	private EmployeeService employeeService;

	@PostMapping(value = "/employee")
	public ResponseEntity<EmployeeDto> createEmployee(@RequestBody EmployeeDto employeeDto) {
		EmployeeDto createdEmployee = employeeService.createEmployee(employeeDto);
		return new ResponseEntity<>(createdEmployee, HttpStatus.CREATED);
	}

	@GetMapping(value = "/employee/{employeeId}")
	public ResponseEntity<EmployeeDto> getEmployeeById(@PathVariable("employeeId") Long employeeId)
			throws EmployeeNotFoundException {
		try {
			EmployeeDto employee = employeeService.getEmployeeById(employeeId);
			return new ResponseEntity<>(employee, HttpStatus.OK);
		} catch (EmployeeNotFoundException employeeNotFoundException) {
			throw employeeNotFoundException;
		}
	}	
}

Test

Let us now test the get employee by id API.
Spring Boot + MySQL get employee by id API
If suppose we try to retrieve an employee that does not exist Let us now test the get employee by id API.
Spring Boot + MySQL get employee exception

Spring Boot + MySQL get employee resource not found exception

Get All Employees


Spring Boot + MySQL Get All Employees Operation

Service Implementation

Next we define EmployeeService interface method named getEmployees(). This method returns a list of EmployeeDto objects.
package com.javainuse.bootmysqlcrud.service;
	
import java.util.List;	

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
	
public interface EmployeeService {
	EmployeeDto createEmployee(EmployeeDto employeeDto);	
	EmployeeDto getEmployeeById(Long employeeId) throws EmployeeNotFoundException;
	List<EmployeeDto> getEmployees();
}
In the EmployeeServiceImpl, we define the getEmployees method that overrides a method with the same signature in the EmployeeService interface. It returns a list of EmployeeDto objects.
Inside the method, it uses the employeeRepository to retrieve a list of Employee objects from MySQL database. Then, it uses the stream method on the list of Employee objects to create a stream, and applies a map operation to each element of the stream. The map operation takes a lambda expression that maps each Employee object to an EmployeeDto object using the EmployeeMapper.mapToEmployeeDto method.
Finally, it uses the collect operation to collect the mapped EmployeeDto objects into a list and returns that list.
package com.javainuse.bootmysqlcrud.service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.entity.Employee;
import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
import com.javainuse.bootmysqlcrud.mapper.EmployeeMapper;
import com.javainuse.bootmysqlcrud.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

	@Autowired
	private EmployeeRepository employeeRepository;

	@Override
	public EmployeeDto createEmployee(EmployeeDto employeeDto) {
		Employee employee = EmployeeMapper.mapToEmployee(employeeDto);
		Employee createdEmployee = employeeRepository.save(employee);
		return EmployeeMapper.mapToEmployeeDto(createdEmployee);
	}

	@Override
	public EmployeeDto getEmployeeById(Long employeeId) throws EmployeeNotFoundException {
		Optional<Employee> employee = employeeRepository.findById(employeeId);
		if (employee.isEmpty()) {
			throw new EmployeeNotFoundException("Employee with id - " + employeeId + " not found.");
		}
		return EmployeeMapper.mapToEmployeeDto(employee.get());
	}

	@Override
	public List<EmployeeDto> getEmployees() {
		List<Employee> employees = employeeRepository.findAll();
		return employees.stream().map((emp) -> EmployeeMapper.mapToEmployeeDto(emp)).collect(Collectors.toList());
	}
}

Controller Implementation

Finally in the EmployeeController class we define the getEmployees method. @GetMapping(value = "/employees") is a mapping annotation that maps the method to the specific URL endpoint "/employees" and specifies that it will handle GET requests. The method implementation retrieves a list of employees using the employeeService.getEmployees() method, which is responsible for fetching the employee data from a data source such as a database. The retrieved list of employees is then wrapped in a ResponseEntity, which is an HTTP response object that allows us to control the HTTP response status and headers. In this case, the ResponseEntity is being created with the list of employees as the response body and HttpStatus.CREATED as the status code. Finally, the ResponseEntity object is returned from the method, indicating that the endpoint response will contain a list of employees.
package com.javainuse.bootmysqlcrud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
import com.javainuse.bootmysqlcrud.service.EmployeeService;

@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class EmployeeController {

	private List<EmployeeDto> employees;

	@Autowired
	private EmployeeService employeeService;

	@PostMapping(value = "/employee")
	public ResponseEntity<EmployeeDto> createEmployee(@RequestBody EmployeeDto employeeDto) {
		EmployeeDto createdEmployee = employeeService.createEmployee(employeeDto);
		return new ResponseEntity<>(createdEmployee, HttpStatus.CREATED);
	}

	@GetMapping(value = "/employee/{employeeId}")
	public ResponseEntity<EmployeeDto> getEmployee(@PathVariable("employeeId") Long employeeId)
			throws EmployeeNotFoundException {
		try {
			EmployeeDto employee = employeeService.getEmployeeById(employeeId);
			return new ResponseEntity<>(employee, HttpStatus.CREATED);
		} catch (EmployeeNotFoundException ex) {
			throw ex;
		}
	}

	@GetMapping(value = "/employees")
	public ResponseEntity<List<EmployeeDto>> getEmployees() {
		List<EmployeeDto> employees = employeeService.getEmployees();
		return new ResponseEntity<>(employees, HttpStatus.OK);
	}
}

Test

Let us now test the get all employees.
Spring Boot + MySQL get employee by id API

Delete Employee By Id API


Spring Boot + MySQL Delete By Id Operation

Service Implementation

The deleteEmployee method in the EmployeeService interface is used to delete an employee record from a database or any other persistence mechanism. It takes in the employeeId as a parameter which specifies the unique identifier for the employee. If the employee with the specified employeeId does not exist, it throws an EmployeeNotFoundException.
package com.javainuse.bootmysqlcrud.service;

import java.util.List;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
	
public interface EmployeeService {
	EmployeeDto createEmployee(EmployeeDto employeeDto);	
	EmployeeDto getEmployeeById(Long employeeId) throws EmployeeNotFoundException;
	List<EmployeeDto> getEmployees();
	void deleteEmployee(Long employeeId) throws EmployeeNotFoundException;
}
The deleteEmployee method deletes an employee from the employee repository based on their ID.
The method takes in a "Long" parameter called "employeeId," representing the ID of the employee to be deleted.
It uses the "employeeRepository" to find the employee with the given ID by calling the "findById" method. This method returns an "Optional<Employee>," which may or may not contain a value.
Next, it checks if the "employee" optional is empty using the "isEmpty" method. If it's empty, it means that the employee with the given ID does not exist in the repository. In this case, the method throws an "EmployeeNotFoundException" with a specific message mentioning the employee ID.
If the employee exists, the method proceeds to delete the employee from the repository by calling the "deleteById" method on the "employeeRepository" with the employeeId parameter.
package com.javainuse.bootmysqlcrud.service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.entity.Employee;
import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
import com.javainuse.bootmysqlcrud.mapper.EmployeeMapper;
import com.javainuse.bootmysqlcrud.repository.EmployeeRepository;

@Service
public class EmployeeServiceImpl implements EmployeeService {

	@Autowired
	private EmployeeRepository employeeRepository;

	@Override
	public EmployeeDto createEmployee(EmployeeDto employeeDto) {
		Employee employee = EmployeeMapper.mapToEmployee(employeeDto);
		Employee createdEmployee = employeeRepository.save(employee);
		return EmployeeMapper.mapToEmployeeDto(createdEmployee);
	}

	@Override
	public EmployeeDto getEmployeeById(Long employeeId) throws EmployeeNotFoundException {
		Optional<Employee> employee = employeeRepository.findById(employeeId);
		if (employee.isEmpty()) {
			throw new EmployeeNotFoundException("Employee with id - " + employeeId + " not found.");
		}
		return EmployeeMapper.mapToEmployeeDto(employee.get());
	}

	@Override
	public List<EmployeeDto> getEmployees() {
		List<Employee> employees = employeeRepository.findAll();
		return employees.stream().map((emp) -> EmployeeMapper.mapToEmployeeDto(emp)).collect(Collectors.toList());
	}

	@Override
	public void deleteEmployee(Long employeeId) throws EmployeeNotFoundException {
		Optional<Employee> employee = employeeRepository.findById(employeeId);
		if (employee.isEmpty()) {
			throw new EmployeeNotFoundException("Employee with id - " + employeeId + " not found.");
		}
		employeeRepository.deleteById(employeeId);
	}
}

Controller Implementation

The deleteEmployees method is a DELETE request mapping method that deletes an employee with the specified employeeId. It throws an EmployeeNotFoundException if the employee with the specified id is not found. After deleting the employee, it returns a ResponseEntity with a status of HttpStatus.NO_CONTENT.
package com.javainuse.bootreactapp.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.javainuse.bootreactapp.exception.EmployeeNotFoundException;
import com.javainuse.bootreactapp.model.EmployeeDto;
import com.javainuse.bootreactapp.service.EmployeeService;

@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class EmployeeController {

	private List<EmployeeDto> employees;

	@Autowired
	private EmployeeService employeeService;

	@PostMapping(value = "/employee")
	public ResponseEntity<EmployeeDto> createEmployee(@RequestBody EmployeeDto employeeDto) {
		EmployeeDto createdEmployee = employeeService.createEmployee(employeeDto);
		return new ResponseEntity<>(createdEmployee, HttpStatus.CREATED);
	}

	@GetMapping(value = "/employee/{employeeId}")
	public ResponseEntity<EmployeeDto> getEmployee(@PathVariable("employeeId") Long employeeId)
			throws EmployeeNotFoundException {
		try {
			EmployeeDto employee = employeeService.getEmployeeById(employeeId);
			return new ResponseEntity<>(employee, HttpStatus.CREATED);
		} catch (EmployeeNotFoundException ex) {
			throw ex;
		}
	}

	@GetMapping(value = "/employees")
	public ResponseEntity<List<EmployeeDto>> getEmployees() {
		List<EmployeeDto> employees = employeeService.getEmployees();
		return new ResponseEntity<>(employees, HttpStatus.CREATED);
	}

	@DeleteMapping(value = "/employee/{employeeId}")
	public ResponseEntity<HttpStatus> deleteEmployees(@PathVariable("employeeId") Long employeeId)
			throws EmployeeNotFoundException {
		employeeService.deleteEmployee(employeeId);
		return new ResponseEntity<>(HttpStatus.NO_CONTENT);
	}
}

Test

Let us now test the delete employee by id api.
Spring Boot + MySQL delete employee by id API

Update Employee API


Spring Boot + MySQL Update Operation

Service Implementation

The updateEmployee method in the EmployeeService interface is used to update the details of an employee. It takes an EmployeeDto object as a parameter, which contains the updated information for the employee. The method returns the updated EmployeeDto object after the update is successful.
If the employee with the specified employeeDto does not exist in the system, the method throws an EmployeeNotFoundException, indicating that the employee could not be updated because they were not found.
package com.javainuse.bootmysqlcrud.service;

import java.util.List;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
	
public interface EmployeeService {
	EmployeeDto createEmployee(EmployeeDto employeeDto);	
	EmployeeDto getEmployeeById(Long employeeId) throws EmployeeNotFoundException;
	List<EmployeeDto> getEmployees();
	void deleteEmployee(Long employeeId) throws EmployeeNotFoundException;
	EmployeeDto updateEmployee(EmployeeDto employeeDto) throws EmployeeNotFoundException;
}
The method updateEmployee in the EmployeeServiceImpl class updates an employee record in the database based on the provided EmployeeDto object.

It first retrieves the employee record from the database using the findById method of the employeeRepository object.
If the retrieved employee is empty (not found), it throws an EmployeeNotFoundException with a message indicating that the employee with the given ID was not found.
If the employee is found, it updates the employee object with the values from the employeeDto object by calling the setName and setDepartment methods on the employee object.
It then saves the updated employee object to the database using the save method of the employeeRepository object.
Finally, it returns a mapped EmployeeDto object based on the saved employee object using the mapToEmployeeDto method of the EmployeeMapper class.
package com.javainuse.bootmysqlcrud.service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.entity.Employee;
import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
import com.javainuse.bootmysqlcrud.mapper.EmployeeMapper;
import com.javainuse.bootmysqlcrud.repository.EmployeeRepository;


@Service
public class EmployeeServiceImpl implements EmployeeService {

	@Autowired
	private EmployeeRepository employeeRepository;

	@Override
	public EmployeeDto createEmployee(EmployeeDto employeeDto) {
		Employee employee = EmployeeMapper.mapToEmployee(employeeDto);
		Employee createdEmployee = employeeRepository.save(employee);
		return EmployeeMapper.mapToEmployeeDto(createdEmployee);
	}

	@Override
	public EmployeeDto getEmployeeById(Long employeeId) throws EmployeeNotFoundException {
		Optional<Employee> employee = employeeRepository.findById(employeeId);
		if (employee.isEmpty()) {
			throw new EmployeeNotFoundException("Employee with id - " + employeeId + " not found.");
		}
		return EmployeeMapper.mapToEmployeeDto(employee.get());
	}

	@Override
	public List<EmployeeDto> getEmployees() {
		List<Employee> employees = employeeRepository.findAll();
		return employees.stream().map((emp) -> EmployeeMapper.mapToEmployeeDto(emp)).collect(Collectors.toList());
	}

	@Override
	public void deleteEmployee(Long employeeId) throws EmployeeNotFoundException {
		Optional<Employee> employee = employeeRepository.findById(employeeId);
		if (employee.isEmpty()) {
			throw new EmployeeNotFoundException("Employee with id - " + employeeId + " not found.");
		}
		employeeRepository.deleteById(employeeId);
	}

	@Override
	public EmployeeDto updateEmployee(EmployeeDto employeeDto) throws EmployeeNotFoundException {
		Optional<Employee> retrievedEmployee = employeeRepository.findById(employeeDto.getId());
		if (retrievedEmployee.isEmpty()) {
			throw new EmployeeNotFoundException("Employee with id - " + employeeDto.getId() + " not found.");
		}
		Employee employee = retrievedEmployee.get();
		employee.setName(employeeDto.getName());
		employee.setDepartment(employeeDto.getDepartment());
		Employee createdEmployee = employeeRepository.save(employee);
		return EmployeeMapper.mapToEmployeeDto(createdEmployee);
	}
}

Controller Implementation

The method updateEmployee in EmployeeController is responsible for updating an employee's information. It takes an EmployeeDto object as a parameter, which contains the updated information for the employee.
Inside the method, it calls the updateEmployee method of the employeeService to update the employee's information. The updated EmployeeDto object is then returned.
Finally, the method creates a new ResponseEntity object using the updated EmployeeDto and specifies the HTTP status code as HttpStatus.OK. This ResponseEntity object is returned as the response.
package com.javainuse.bootmysqlcrud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.javainuse.bootmysqlcrud.dto.EmployeeDto;
import com.javainuse.bootmysqlcrud.exception.EmployeeNotFoundException;
import com.javainuse.bootmysqlcrud.service.EmployeeService;

@RestController
public class EmployeeController {

	private List<EmployeeDto> employees;

	@Autowired
	private EmployeeService employeeService;

	@PostMapping(value = "/employee")
	public ResponseEntity<EmployeeDto> createEmployee(@RequestBody EmployeeDto employeeDto) {
		EmployeeDto createdEmployee = employeeService.createEmployee(employeeDto);
		return new ResponseEntity<>(createdEmployee, HttpStatus.CREATED);
	}

	@GetMapping(value = "/employee/{employeeId}")
	public ResponseEntity<EmployeeDto> getEmployee(@PathVariable("employeeId") Long employeeId)
			throws EmployeeNotFoundException {
		try {
			EmployeeDto employee = employeeService.getEmployeeById(employeeId);
			return new ResponseEntity<>(employee, HttpStatus.CREATED);
		} catch (EmployeeNotFoundException ex) {
			throw ex;
		}
	}

	@GetMapping(value = "/employees")
	public ResponseEntity<List<EmployeeDto>> getEmployees() {
		List<EmployeeDto> employees = employeeService.getEmployees();
		return new ResponseEntity<>(employees, HttpStatus.CREATED);
	}

	@DeleteMapping(value = "/employee/{employeeId}")
	public ResponseEntity<HttpStatus> deleteEmployees(@PathVariable("employeeId") Long employeeId)
			throws EmployeeNotFoundException {
		employeeService.deleteEmployee(employeeId);
		return new ResponseEntity<>(HttpStatus.NO_CONTENT);

	}

	@PutMapping(value = "/employee")
	public ResponseEntity<EmployeeDto> updateEmployee(@RequestBody EmployeeDto employeeDto)
			throws EmployeeNotFoundException {
		EmployeeDto createdEmployee = employeeService.updateEmployee(employeeDto);
		return new ResponseEntity<>(createdEmployee, HttpStatus.OK);
	}
}

Test

Let us now test the update employee by id.
Spring Boot + MySQL update employee by id API

Spring Boot + MySQL update employee table

Download Source Code

Download it -
Spring Boot 3 + MySQL CRUD Example