查詢方法

標準的 CRUD 功能 Repository 通常需要對底層資料儲存執行查詢。使用 Spring Data,宣告這些查詢分為四個步驟:

  1. 宣告一個擴充套件 Repository 或其子介面之一的介面,並將其型別與應處理的領域類和 ID 型別關聯起來,如下例所示:

    interface PersonRepository extends Repository<Person, Long> { … }
  2. 在介面上宣告查詢方法。

    interface PersonRepository extends Repository<Person, Long> {
      List<Person> findByLastname(String lastname);
    }
  3. 配置 Spring 以建立這些介面的代理例項,可以使用 JavaConfigXML 配置

    • 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… 屬性之一。

  4. 注入 Repository 例項並使用它,如下例所示:

    class SomeClient {
    
      private final PersonRepository repository;
    
      SomeClient(PersonRepository repository) {
        this.repository = repository;
      }
    
      void doSomething() {
        List<Person> persons = repository.findByLastname("Matthews");
      }
    }

以下各節詳細解釋每個步驟。