Monday, 23 December 2019

Spring boot WebFlux: Adding controllers to the application


Get all employees
@RequestMapping(value = "employees", method = RequestMethod.GET)
public Flux<Employee> all() {
         return empRepository.findAll();
}

Delete All employees
@RequestMapping(value = "employees", method = RequestMethod.DELETE)
public Mono<Void> deleteAll() {
         return empRepository.deleteAll();
}

Get Employee by id
@RequestMapping(value = "employees/{id}", method = RequestMethod.GET)
public Mono<ResponseEntity<Employee>> byId(@PathVariable("id") String id) {
         return empRepository.findById(id).map(emp -> ResponseEntity.ok(emp)).defaultIfEmpty(ResponseEntity.notFound().build());
}

Update employee by id
@RequestMapping(value = "employees/{id}", method = RequestMethod.PUT)
public Mono<ResponseEntity<Employee>> update(@PathVariable("id") String id, @RequestBody Employee emp) {

         return empRepository.findById(id).flatMap(persistedEmp -> {
                  persistedEmp.setFirstName(emp.getFirstName());
                  persistedEmp.setLastName(emp.getLastName());
                  return empRepository.save(persistedEmp);
         }).map(persistedEmp -> ResponseEntity.status(HttpStatus.CREATED).body(persistedEmp))
                           .defaultIfEmpty(ResponseEntity.notFound().build());
}

Delete employee by id
@RequestMapping(value = "employees/{id}", method = RequestMethod.DELETE)
public Mono<ResponseEntity<Void>> delete(@PathVariable("id") String id) {

         return empRepository.findById(id)
                           .flatMap(persistedEmployee -> empRepository.delete(persistedEmployee)
                                             .then(Mono.just(ResponseEntity.ok().<Void>build())))
                           .defaultIfEmpty(ResponseEntity.notFound().build());

}

Create new employee
@RequestMapping(value = "employees", method = RequestMethod.POST)
public Mono<ResponseEntity<Employee>> create(@RequestBody Employee emp) {
         return empRepository.save(emp).map(persistedEmp -> ResponseEntity.status(HttpStatus.CREATED).body(persistedEmp));
}

Find the below working application.

Employee.java
package com.sample.app.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Employee {

 @Id
 private String id;
 
 private String firstName;

 private String lastName;

 public Employee() {
 }

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

 public String getFirstName() {
  return firstName;
 }

 public String getId() {
  return id;
 }

 public String getLastName() {
  return lastName;
 }

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

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

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

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=")
    .append(lastName).append("]");
  return builder.toString();
 }

}


EmployeeRepository.java
package com.sample.app.repository;

import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;

import com.sample.app.entity.Employee;

import reactor.core.publisher.Flux;

@Repository
public interface EmployeeRepository extends ReactiveMongoRepository<Employee, String> {

 public Flux<Employee> findByFirstName(String firstName);
}


EmployeeController.java
package com.sample.app.comntroller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
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.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

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

 @Autowired
 private EmployeeRepository empRepository;

 @RequestMapping(value = "employees", method = RequestMethod.GET)
 public Flux<Employee> all() {
  return empRepository.findAll();
 }

 @RequestMapping(value = "employees", method = RequestMethod.DELETE)
 public Mono<Void> deleteAll() {
  return empRepository.deleteAll();
 }

 @RequestMapping(value = "employees/{id}", method = RequestMethod.GET)
 public Mono<ResponseEntity<Employee>> byId(@PathVariable("id") String id) {
  return empRepository.findById(id).map(emp -> ResponseEntity.ok(emp))
    .defaultIfEmpty(ResponseEntity.notFound().build());
 }

 @RequestMapping(value = "employees/{id}", method = RequestMethod.PUT)
 public Mono<ResponseEntity<Employee>> update(@PathVariable("id") String id, @RequestBody Employee emp) {

  return empRepository.findById(id).flatMap(persistedEmp -> {
   persistedEmp.setFirstName(emp.getFirstName());
   persistedEmp.setLastName(emp.getLastName());
   return empRepository.save(persistedEmp);
  }).map(persistedEmp -> ResponseEntity.status(HttpStatus.CREATED).body(persistedEmp))
    .defaultIfEmpty(ResponseEntity.notFound().build());
 }

 @RequestMapping(value = "employees/{id}", method = RequestMethod.DELETE)
 public Mono<ResponseEntity<Void>> delete(@PathVariable("id") String id) {

  return empRepository.findById(id)
    .flatMap(persistedEmployee -> empRepository.delete(persistedEmployee)
      .then(Mono.just(ResponseEntity.ok().<Void>build())))
    .defaultIfEmpty(ResponseEntity.notFound().build());

 }

 @RequestMapping(value = "employees", method = RequestMethod.POST)
 public Mono<ResponseEntity<Employee>> create(@RequestBody Employee emp) {
  return empRepository.save(emp)
    .map(persistedEmp -> ResponseEntity.status(HttpStatus.CREATED).body(persistedEmp));
 }

}


App.java
package com.sample.app;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.sample.app.entity.Employee;
import com.sample.app.repository.EmployeeRepository;

import reactor.core.publisher.Flux;

@SpringBootApplication
public class App {
 public static void main(String[] args) {

  SpringApplication.run(App.class, args);
 }

 @Bean
 public CommandLineRunner demo(EmployeeRepository empRepository) {
  return (args) -> {
   Employee emp1 = new Employee("Phalgun", "Garimella");
   Employee emp2 = new Employee("Sankalp", "Dubey");
   Employee emp3 = new Employee("Arpan", "Debroy");

   Flux<Employee> empsFlux = Flux.just(emp1, emp2, emp3);

   empsFlux.map(emp -> empRepository.save(emp))
     .subscribe(result -> System.out.println("Created employee : " + result.block()));

   System.out.println("\nGetting all the employees from database\n");
   empRepository.findAll().subscribe(System.out::println);

  };
 }
}


pom.xml
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>springWebflux</groupId>
 <artifactId>springWebflux</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>


 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-webflux</artifactId>
  </dependency>

  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-mongodb-reactive</artifactId>
  </dependency>


  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>

  <dependency>
   <groupId>de.flapdoodle.embed</groupId>
   <artifactId>de.flapdoodle.embed.mongo</artifactId>
   <!-- <scope>test</scope> -->
  </dependency>


 </dependencies>
</project>


Total project structure looks like below.

Run App.java.

Open any rest client like postman and perform below operations.

Get all employees
Method: GET

API: localhost:8080/api/v1/employees

Get specific employee
Method: GET

API: localhost:8080/api/v1/employees/{employee_id}

Update an employee
Method: PUT
API: localhost:8080/api/v1/employees/{employeeId}
Body:
{
    "firstName": "rama",
    "lastName": "Krishna"
}
Delete an Employee

Method: DELETE
API: localhost:8080/api/v1/employees/{employee_id}

Delete all employees
Method: DELETE
API: localhost:8080/api/v1/employees/




Previous                                                    Next                                                    Home

No comments:

Post a Comment