Java 學習記錄138 — 員工管理系統專案練習-Creating Get Employee By Id REST API

接著繼續寫查詢特定員工的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

--

--

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

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