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

接著繼續寫更新特定員工的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”

--

--

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

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