对于最新的稳定版本,请使用 Spring Data Commons 3.3.1Spring中文文档

对于最新的稳定版本,请使用 Spring Data Commons 3.3.1Spring中文文档

标准 CRUD 功能存储库通常对基础数据存储库进行查询。 使用 Spring Data,声明这些查询将分为四个步骤:Spring中文文档

  1. 声明扩展 Repository 或其子接口之一的接口,并将其键入为应处理的域类和 ID 类型,如以下示例所示:Spring中文文档

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

    interface PersonRepository extends Repository<Person, Long> {
      List<Person> findByLastname(String lastname);
    }
  3. 设置 Spring 以使用 JavaConfigXML 配置为这些接口创建代理实例。Spring中文文档

    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 命名空间。 如果将存储库抽象用于任何其他存储,则需要将其更改为存储模块的相应命名空间声明。 换句话说,您应该交换支持,例如,.jpamongodbSpring中文文档

    请注意,JavaConfig 变体不会显式配置包,因为缺省情况下使用带注释的类的包。 要自定义要扫描的包,请使用特定于数据存储库的 -annotation 的属性之一。basePackage…@EnableJpaRepositoriesSpring中文文档

  4. 注入存储库实例并使用它,如以下示例所示:Spring中文文档

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

以下各节详细介绍了每个步骤:Spring中文文档