跳到主要内容

查询方法

DeepSeek V3 中英对照 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. 使用 JavaConfigXML 配置 设置 Spring 为这些接口创建代理实例。

    import org.springframework.data..repository.config.EnableNeo4jRepositories;

    @EnableNeo4jRepositories
    class Config {}
    java

    本例中使用了 JPA 命名空间。如果你为其他存储库使用存储库抽象,则需要将其更改为存储模块的适当命名空间声明。换句话说,你应该将 jpa 替换为例如 mongodb

    请注意,JavaConfig 变体没有显式配置包,因为默认使用带注解类的包。要自定义要扫描的包,请使用数据存储特定的存储库的 @EnableNeo4jRepositories 注解的 basePackage… 属性之一。

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

    class SomeClient {

    private final PersonRepository repository;

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

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

接下来的章节将详细解释每个步骤: