查詢方法
標準 CRUD 功能儲存庫通常在底層資料儲存上具有查詢。 使用 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.EnableNeo4jRepositories; @EnableNeo4jRepositories 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 變體沒有顯式配置包,因為預設情況下使用帶註釋的類的包。 要自定義要掃描的包,請使用資料儲存特定儲存庫的
@EnableNeo4jRepositories
註釋的basePackage…
屬性之一。 -
-
注入儲存庫例項並使用它,如以下示例所示
class SomeClient { private final PersonRepository repository; SomeClient(PersonRepository repository) { this.repository = repository; } void doSomething() { List<Person> persons = repository.findByLastname("Matthews"); } }
以下各節詳細解釋了每個步驟