接著繼續寫刪除特定員工的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 比較是刪除常用的狀態碼

我這裡傾向用第二個版本

到此增刪改查都寫完了

本專案完成

--

--

接著繼續寫更新特定員工的API

EmployeeController.java

// update employee by id - version 1
@PutMapping("/employees/{id}")
public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee newEmployee) {
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee ID not found:" + id));
employee.setFirstName(newEmployee.getFirstName());
employee.setLastName(newEmployee.getLastName());
employee.setemailId(newEmployee.getemailId());
return employeeRepository.save(employee);
}
// update employee by id - version 2
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody Employee newEmployee) {
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee ID not found:" + id));
employee.setFirstName(newEmployee.getFirstName());
employee.setLastName(newEmployee.getLastName());
employee.setemailId(newEmployee.getemailId());
Employee updateEmployee = employeeRepository.save(employee); return ResponseEntity.ok(updateEmployee);
}

兩個版本,一樣的功能

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

之後就 set 改對應的資料,改好後就返回,就大功告成

測試方法:

打開 Postman

改成 PUT

先來改 ID 為 1 的員工

http://localhost:8080/api/v1/employees/1

在 Headers 裡新增一組

KEY:Content-Type、VALUE:application/json

接者在 BODY 裡,填上要更新員工的內容

例如:

{
"firstName": "Tom1",
"lastName": "Cruise1",
"emailId": "tom_cruise@gmail.com"
}

看到顯示 Status:200 OK

去資料庫看,應該會發現資料已經被更新了

如果測一個不存在的ID

http://localhost:8080/api/v1/employees/222

則會顯示 Status:404 Not Found

自訂義訊息則會寫:

“message”: “Employee ID not found:222”

--

--

接著繼續寫查詢特定員工的API

EmployeeController.java

// read employee by id - Version 1
@GetMapping("/employees/{id}")
public Employee getEmployeeById(@PathVariable Long id) {
return employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee ID not found:" + id));
}// read employee by id - version 2
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) {
Employee employee = employeeRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee ID not found:" + id));
return ResponseEntity.ok(employee);
}

這兩個是同一功能,選一個用即可

上面第一版是我看 sping官網 裡面的例子

下面第二版是老師寫的,返回的是 Http status

老師沒特別講原因,既然兩個結果都一樣,這邊我選擇參考官網的寫法

測試方法:

打開 Postman,選 GET

先測已經有紀錄的ID

http://loclhost:8080/api/v1/employees/3

Status 返回 200

再測沒有的ID

http://localhost:8080/api/v1/employees/8

Status 返回 404

--

--

前面已經完成跟驗證過第一隻 API 了

接著繼續寫,新增員工的 API

EmployeeController.java

// creat employee
@PostMapping("/employees")
public Employee createEmployee(@RequestBody Employee employee) {
return employeeRepository.save(employee);
}

寫完了,還滿簡單的吧

測試方法:

打開 Postman,記得改成 POST http://localhost:8080/api/v1/employees

在 Headers 裡新增一組

KYE:Content-Type

VALUE:application/json

接者在 BODY 裡,填上要新增員工的內容,例如:

{
"firstName": "Chris",
"lastName": "Evans",
"emailId": "Chris_Evans@gmail.com"
}

看到顯示 Status:200 OK

去資料庫看,應該會發現資料已經被新增了

--

--

src/main/java/exception 新增檔案 ResourceNotFoundException.java

package exception;import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
public static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message) {
super(message);
}
}

若數據庫查不到資料的話,就可以使用自定義Exception

返回給客戶端對應的狀態 HttpStatus.NOT_FOUND

--

--