跳到主要内容

查询方法

Doubao 中英对照 Query Methods

标准的 CRUD 功能仓库通常会对底层数据存储进行查询。借助 Spring Data,声明这些查询成为一个四步流程:

  1. 声明一个扩展了 Repository 或其子接口之一的接口,并将其类型指定为它应处理的领域类与 ID 类型,如下例所示:

    interface PersonRepository extends Repository<Person, Long> { … }
    java
  2. 在接口上声明查询方法。

    interface PersonRepository extends Repository<Person, Long> {
    List<Person> findByLastname(String lastname);
    }
    java
  3. 配置 Spring 为这些接口创建代理实例,方式可以是使用 JavaConfig 或 XML 配置。

    import org.springframework.data.….repository.config.EnableJpaRepositories;

    @EnableJpaRepositories
    class Config { … }
    java

    本例使用了 JPA 命名空间。如果您将仓库抽象用于任何其他存储,则需要将其更改为您所用存储模块的相应命名空间声明。换言之,您应当将 jpa 替换为例如 mongodb。

    请注意,JavaConfig 变体并未显式配置包,因为默认使用被注解类所在的包。要自定义要扫描的包,请使用特定数据存储仓库的 @EnableJpaRepositories-注解的 basePackage… 属性之一。

  4. 注入仓库实例并使用它,如下例所示:

    class SomeClient {

    private final PersonRepository repository;

    SomeClient(PersonRepository repository) {
    this.repository = repository;
    }

    void doSomething() {
    List<Person> persons = repository.findByLastname("Matthews");
    }
    }
    java

以下各节将详细解释每个步骤: