In this tutorial, we will build a 'Delete Employee' REST API with MySQL database and then we will demonstrate how to consume it using WebClient.
1. Building a 'Delete Employee' REST API in Spring Boot
First, you'll set up a Spring Boot application with a MySQL database to store and delete employee data. Then, you'll create a service to handle data persistence and finally use WebClient to delete an employee's data. Let's get started.
Step 1: Set Up the Spring Boot Project with MySQL
Add the necessary dependencies to your pom.xml:
<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>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
Step 2: Configure MySQL Database
Set up your application.properties or application.yml with your MySQL configuration:
spring.datasource.url=jdbc:mysql://localhost:3306/your_database spring.datasource.username=your_username spring.datasource.password=your_password spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
Replace your_database, your_username, and your_password with your actual MySQL database name and credentials.
Step 3: Create the Employee Entity and Repository
Define an Employee entity and a corresponding repository.
import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter @Table(name = "employees") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String department; // Constructors, getters, and setters can be omitted for brevity (use Lombok) }
import org.springframework.data.jpa.repository.JpaRepository; public interface EmployeeRepository extends JpaRepository<Employee, Long> { // Custom methods if needed }
Step 4: Implement the Service Layer
Create a service to handle CRUD operations.
EmployeeService.java:import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class EmployeeService { private final EmployeeRepository employeeRepository; @Autowired public EmployeeService(EmployeeRepository employeeRepository) { this.employeeRepository = employeeRepository; } public void deleteEmployee(Long id) { employeeRepository.deleteById(id); } }
Step 5: Create the REST Controller
Create the REST controller that exposes the DELETE operation:
EmployeeController.java:import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/employees") public class EmployeeController { private final EmployeeService employeeService; @Autowired public EmployeeController(EmployeeService employeeService) { this.employeeService = employeeService; } @DeleteMapping("/{id}") public ResponseEntity<?> deleteEmployee(@PathVariable Long id) { employeeService.deleteEmployee(id); return ResponseEntity.noContent().build(); } }
2. Consuming the API with WebClient
Step 1: Configure WebClient
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.client.WebClient; @Configuration public class WebClientConfig { @Bean public WebClient webClient() { return WebClient.builder() .baseUrl("http://localhost:8080/api/employees") .build(); } }
Step 2: Implement WebClient Service
Implement WebClient Service Create a service that uses WebClient to send a DELETE request:
WebClientService.java:import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Mono; @Service public class WebClientService { private final WebClient webClient; @Autowired public WebClientService(WebClient webClient) { this.webClient = webClient; } public Mono<Void> deleteEmployee(Long id) { return webClient.delete() .uri("/{id}", id) .retrieve() .bodyToMono(Void.class); } }
In the deleteEmployee method, the URI is constructed with the employee ID as a path variable, and the response is converted to a Mono<Void> indicating the completion of the operation.
Step 3: Use WebClient Service in the Application
Finally, you can use the WebClientService from any part of your application to trigger the delete operation:
ApplicationRunner.java:import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class ApplicationRunner implements CommandLineRunner { private final WebClientService webClientService; public ApplicationRunner(WebClientService webClientService) { this.webClientService = webClientService; } @Override public void run(String... args) { webClientService.deleteEmployee(1L) .subscribe( null, error -> System.err.println("Error during deletion: " + error), () -> System.out.println("Deletion completed!") ); } }
Comments
Post a Comment