Based on this "package com.luv2code.springboot.cruddemo.rest; import…
- User
Based on this "package com.luv2code.springboot.cruddemo.rest;
import com.luv2code.springboot.cruddemo.entity.Employee; import com.luv2code.springboot.cruddemo.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.Optional;
@RestController @RequestMapping("/api") public class EmployeeRestController { private final EmployeeService employeeService;
code@Autowired public EmployeeRestController(EmployeeService employeeService) { this.employeeService = employeeService; } @GetMapping("/employees") public List<Employee> findAll() { return this.employeeService.findAll(); } @GetMapping("/employees/{employeeId}") public Employee findById(@PathVariable int employeeId) { Optional<Employee> result = employeeService.findById(employeeId); if (result.isEmpty()) { throw new RuntimeException("Employee id not found - " + employeeId); } Employee theEmployee = result.get(); return theEmployee; } @PostMapping("/employees") public Employee addEmployee(@RequestBody Employee theEmployee) { theEmployee.setId(0); Employee dbEmployee = employeeService.save(theEmployee); return dbEmployee; } @PutMapping("/employees") public Employee updateEmployee(@RequestBody Employee theEmployee) { Employee dbEmployee = employeeService.save(theEmployee); return dbEmployee; } @DeleteMapping("/employees/{employeeId}") public Employee deleteEmployee(@PathVariable int employeeId) { Employee tempEmployee = employeeService.deletebyId(employeeId); if (tempEmployee == null) { throw new RuntimeException("Employee id not found - " + employeeId); } employeeService.deletebyId(employeeId); return tempEmployee; } - Assistant