查詢方法
標準 CRUD 功能儲存庫通常會對底層資料儲存區進行查詢。 透過 Spring Data,宣告這些查詢變成四個步驟的流程
-
宣告一個介面,擴充 Repository 或其子介面之一,並將其類型設定為應處理的網域類別和 ID 類型,如下列範例所示
interface PersonRepository extends Repository<Person, Long> { … }
-
在介面上宣告查詢方法。
interface PersonRepository extends Repository<Person, Long> { List<Person> findByLastname(String lastname); }
-
設定 Spring 以為這些介面建立 Proxy 實例,可使用 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 命名空間。 如果您將儲存庫抽象用於任何其他儲存區,則需要將其變更為您儲存模組的適當命名空間宣告。 換句話說,您應該將
jpa
換成例如mongodb
。請注意,JavaConfig 變體未明確組態套件,因為預設會使用已註釋類別的套件。 若要自訂要掃描的套件,請使用資料儲存區特定儲存庫
@EnableJpaRepositories
註釋的basePackage…
屬性之一。 -
-
注入儲存庫實例並加以使用,如下列範例所示
class SomeClient { private final PersonRepository repository; SomeClient(PersonRepository repository) { this.repository = repository; } void doSomething() { List<Person> persons = repository.findByLastname("Matthews"); } }
以下各節詳細說明每個步驟