在 src/main/java/controller
建立 EmployeeController.java
package controller;import model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import repository.EmployeeRepository;import java.util.List;@RestController
@RequestMapping("/api/v1")
public class EmployeeController { @Autowired
private EmployeeRepository employeeRepository; // get all employees
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
}
這就是之前創 Repository extends JpaRepository 的好處
直接使用人家寫好的 findAll()
返回一個含有所有員工的 List
@Autowired
private EmployeeRepository employeeRepository;
Intellij 會在 @Autowired
提示:Field injection is not recommended
可以改成下面這樣
private EmployeeRepository employeeRepository;@Autowired
public void setEmployeeRepository(EmployeeRepository employeeRepository) {
this.employeeRepository = employeeRepository;
}
接著準備來測試這個API
運行主程式 SpringbootBackendApplication.java
檢查有無產生 employees 的 table
結果我在這邊卡了兩、三天
死活都沒看到自動生成 table
google 查詢其他文章怎麼處理
查了幾篇,照著改配置,怎改都沒用
最後終於找到解法
Your Entity classes should be in the same or in a sub-package relative to where you have you class with @EnableAutoConfiguration. If that’s not trye, your Spring Boot application simply cannot detect them and hence will not create your Database tables.
額,原來是當初眼花,在前面 132. 員工管理系統專案練習-Create JPA Entity
新增的四個資料夾弄錯位置,要跟主程式入口放同一個位置,我放到上上上一級去了
當初:src\main\java
正確:src\main\java\com\example\springbootbackend
大家路徑可能不一樣,反正要跟 SpringbootBackendApplication.java 同個層級就是
看到 table 出來了,代表一切都正常
先自己手動新增幾筆資料進去,準備來測試
我是直接用 Intellij 連資料庫來新增資料
到最右邊那一排,選 database,找到 table,找到 employees 後,點兩下進入表格
依序填入 1,tom_cruise@gmail.com,Tom,Cruise
填好後,上面一點點的地方,眼睛旁邊有個三點五磁片圖案的 sumbit 按下去就成功了,快捷:Ctrl + Enter
先打開瀏覽器,網址貼上:http://localhost:8080/api/v1/employees
也可以用 Postman,選 GET 後,一樣貼上面那串
若有看到資料,就代表成功
到這邊就架好了第一隻 API,其實還算是滿簡單的
從頭稍微複習一下,截至目前,做了以下操作
- 到 application.properties 文件裡,填上資料庫相關資訊
- 新增 model 資料夾,裡面添加 table 的結構
- 新增 repository 資料夾,裡面添加對應 table 的 repository ,
extends JpaRepository
來使用人家寫好的常用方法 - 新增 exception 資料夾,裡面添加自定義的 exception
- 新增 controller 資料夾,裡面寫對應 table 的 API