对于最新的稳定版本,请使用 Spring Data Commons 4.0.4spring-doc.cadn.net.cn

查询方法

标准的 CRUD 功能仓库通常会对底层数据存储执行查询。 在 Spring Data 中,声明这些查询是一个四步过程:spring-doc.cadn.net.cn

  1. 声明一个接口,该接口需继承 Repository 或其某个子接口,并将其泛型化为应处理的领域类和 ID 类型,如下例所示:spring-doc.cadn.net.cn

    interface PersonRepository extends Repository<Person, Long> { … }
  2. 在接口上声明查询方法。spring-doc.cadn.net.cn

    interface PersonRepository extends Repository<Person, Long> {
      List<Person> findByLastname(String lastname);
    }
  3. 设置 Spring 以创建这些接口的代理实例,可使用 JavaConfigXML 配置spring-doc.cadn.net.cn

    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 替换为例如 mongodbspring-doc.cadn.net.cn

    请注意,JavaConfig 变体不会显式配置包,因为默认会使用带注解类所在的包。 若要自定义要扫描的包,请使用特定于数据存储的仓库的 basePackage… 注解中的某个 @EnableJpaRepositories 属性。spring-doc.cadn.net.cn

  4. 注入仓库实例并使用它,如下例所示:spring-doc.cadn.net.cn

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

以下各节将详细解释每个步骤:spring-doc.cadn.net.cn