查詢方法
標準 CRUD 功能的 repositories 通常會對底層資料儲存區進行查詢。透過 Spring Data,宣告這些查詢變成四個步驟的流程
-
宣告一個介面,擴展 Repository 或其子介面之一,並將其類型設定為它應處理的網域類別和 ID 類型,如下列範例所示
interface PersonRepository extends Repository<Person, Long> { … }
-
在介面上宣告查詢方法。
interface PersonRepository extends Repository<Person, Long> { List<Person> findByLastname(String lastname); }
-
設定 Spring 以為這些介面建立代理實例,可以使用JavaConfig 或XML 配置。
-
Java
-
XML
import org.springframework.data.….repository.config.EnableJpaRepositories; @EnableJpaRepositories class Config { … }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/jpa https://www.springframework.org/schema/data/jpa/spring-jpa.xsd"> <repositories base-package="com.acme.repositories"/> </beans>
在此範例中使用了 JPA 命名空間。如果您將 repository 抽象概念用於任何其他儲存區,則需要將其變更為您的儲存模組的適當命名空間宣告。換句話說,您應該將
jpa
替換為,例如mongodb
。請注意,JavaConfig 變體未明確配置套件,因為預設會使用帶註解類別的套件。若要自訂要掃描的套件,請使用資料儲存區特定 repository 的
@EnableJpaRepositories
註解的basePackage…
屬性之一。 -
-
注入 repository 實例並使用它,如下列範例所示
class SomeClient { private final PersonRepository repository; SomeClient(PersonRepository repository) { this.repository = repository; } void doSomething() { List<Person> persons = repository.findByLastname("Matthews"); } }
以下章節詳細說明每個步驟