Java 學習記錄140 — 員工管理系統專案練習-Creating Delete Employee REST API

接著繼續寫刪除特定員工的API

EmployeeController.java

//     delete employees by id - version 1
@DeleteMapping("/employees/{id}")
public ResponseEntity<Map<String, Boolean>> deleteEmployee(@PathVariable Long id) {
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee ID not found:" + id));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("delete", Boolean.TRUE);
return ResponseEntity.ok(response);
}
// delete employees by id - version 2
@DeleteMapping("/employees/{id}")
public ResponseEntity<Long> deleteEmployee(@PathVariable Long id) {
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee ID not found:" + id));
employeeRepository.delete(employee);
return new ResponseEntity<>(id, HttpStatus.NO_CONTENT);
}

還是兩個版本,一樣的功能

一樣是先利用 getEmployeeById() 裡面的功能,先確認有沒有對應ID的員工,有的話就獲得 employee,沒有的話就報錯

找到之後就 直接刪除跟回傳狀態

版本一是老師寫的,回傳一個MAP,裡面附上文字輸出,Status: 200 ok

{
"delete": true
}

版本二是網路上查的,沒有回傳內容,但 Status: 204 No Content 比較是刪除常用的狀態碼

我這裡傾向用第二個版本

到此增刪改查都寫完了

本專案完成

--

--

記錄成為軟體工程師的過程

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store