首先,創建一個 Spring Boot 應用程序,該應用程序包含構建只讀 API 所需的依賴項。您需要以下組件:
在開發階段,可以使用 H2 數據庫快速完成設置,而在生產環境中可以切換到 MySQL 或 PostgreSQL。
Spring Boot 默認會嘗試自動配置數據源。如果無法連接數據源,應用程序將在啟動時拋出錯誤。以下是一個簡單的 H2 數據庫配置示例,您可以將其添加到 application.properties 文件中:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
以上配置使用內存數據庫,您無需安裝或配置額外的數據庫即可進行測試。
只讀 API 仍然需要讀取數據。在這里,我們以“產品”實體為例。以下是一個簡單的實體類示例:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String category;
private Double price; // 構造函數和 getter 方法
}
注意,這里沒有 setter 方法。這是為了確保 API 僅支持只讀操作。數據可以通過構造函數設置,或者在數據庫初始化時進行預加載。
存儲庫接口是 Spring Data JPA 的核心。通過擴展 JpaRepository,您可以直接使用許多內置方法,例如 findAll() 和 findById()。此外,您還可以通過命名方法來定義自定義查詢。例如:
public interface ProductRepository extends JpaRepository {
List findByCategory(String category);
List findByNameContaining(String keyword);
List findByPriceLessThan(Double maxPrice);
}
無需編寫 SQL 或 JPQL,Spring 會根據方法名自動生成查詢邏輯。這種方式適用于小型數據集。如果需要分頁,可以通過 Pageable 接口實現。
控制器負責定義 HTTP 端點,并通過構造函數注入存儲庫。以下是一個示例控制器:
@RestController
@RequestMapping("/products")
public class ProductController {
private final ProductRepository repository; public ProductController(ProductRepository repository) {
this.repository = repository;
} @GetMapping
public List getAll() {
return repository.findAll();
} @GetMapping("/category/{category}")
public List byCategory(@PathVariable String category) {
return repository.findByCategory(category);
} @GetMapping("/search")
public List byName(@RequestParam String keyword) {
return repository.findByNameContaining(keyword);
} @GetMapping("/under/{price}")
public List cheaperThan(@PathVariable Double price) {
return repository.findByPriceLessThan(price);
}
}
每個方法都會返回存儲庫查詢的結果,直接以 JSON 格式響應。控制器本身不包含業務邏輯,僅負責路由請求。這種設計簡潔高效,適用于公共或內部 API。
Spring Data JPA 根據方法名生成查詢邏輯。常見的前綴包括 findBy、readBy 和 getBy,后接字段名(使用駝峰命名法)。例如:
List findByStatus(String status);
Spring 會將其解析為類似 SELECT * FROM customer WHERE status = ? 的查詢。如果需要組合條件,可以使用 And 或 Or:
List findByStatusAndCity(String status, String city);
這種命名約定支持多種條件組合,并且無需顯式定義查詢字符串。
Spring 提供了一組關鍵字,用于生成基于模式匹配、比較或列表過濾的查詢。以下是一些常見關鍵字及其用法:
List findByNameContaining(String keyword);
轉換為 SQL 的 LIKE 查詢。
LessThan、GreaterThan 和 Between。 List findByTotalLessThan(Double maxTotal);
List findByDateBetween(LocalDate start, LocalDate end);
List findByActiveTrue();
關鍵字列表定義明確,確保方法名可讀且易于維護。
對于大數據集,分頁和排序是必不可少的功能。通過在方法中添加 Pageable 參數,Spring 可以自動處理分頁和排序。例如:
Page findByGenre(String genre, Pageable pageable);
控制器示例:
@GetMapping("/genre/{genre}")
public Page byGenre(@PathVariable String genre, Pageable pageable) {
return bookRepository.findByGenre(genre, pageable);
}
客戶端可以通過查詢參數指定分頁和排序規則,例如:/genre/fiction?page=0&size=5&sort=title,asc。
如果只需要排序,可以使用 OrderBy 關鍵字:
List findByDepartmentOrderByLastNameAsc(String department);
通過 Spring Boot 和 Spring Data JPA,您可以快速構建高效的只讀 API。只需遵循方法命名約定,Spring 會自動生成查詢邏輯,簡化了開發過程??刂破髫撠熉酚烧埱?,而存儲庫則處理數據操作。無論是簡單查詢還是復雜條件,Spring 提供了強大的支持,使開發者能夠專注于業務邏輯而非底層實現。
原文鏈接: https://medium.com/@AlexanderObregon/building-read-only-apis-with-spring-boot-and-query-methods-8d8b3b012672