Query Methods

标准 CRUD 功能存储库通常针对底层数据存储具有查询。使用 Spring Data,声明这些查询会变成一个四步过程:

Standard CRUD functionality repositories usually have queries on the underlying datastore. With Spring Data, declaring those queries becomes a four-step process:

  1. Declare an interface extending Repository or one of its subinterfaces and type it to the domain class and ID type that it should handle, as shown in the following example:[source, java]

interface PersonRepository extends Repository<Person, Long> { … }
  1. Declare query methods on the interface.[source, java]

interface PersonRepository extends Repository<Person, Long> {
  List<Person> findByLastname(String lastname);
}
  1. Set up Spring to create proxy instances for those interfaces, either with JavaConfig or with XML configuration.

Java
import org.springframework.data.….repository.config.Enable{store}Repositories;

@Enable{store}Repositories
class Config { … }
XML
<?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 名称空间。如果您对任何其他存储使用存储库抽象,则需要将其更改为您存储模块的相应名称空间声明。换句话说,您应该用 mongodb 代替 jpa

The JPA namespace is used in this example. If you use the repository abstraction for any other store, you need to change this to the appropriate namespace declaration of your store module. In other words, you should exchange jpa in favor of, for example, mongodb.

请注意,JavaConfig 变体不会显式地配置包,因为默认情况下使用带注释类的包。要自定义要扫描的包,请使用数据存储特定存储库的 @Enable{store}Repositories 注释的 basePackage… 属性之一。

Note that the JavaConfig variant does not configure a package explicitly, because the package of the annotated class is used by default. To customize the package to scan, use one of the basePackage… attributes of the data-store-specific repository’s @Enable{store}Repositories-annotation. . Inject the repository instance and use it, as shown in the following example:[source, java]

class SomeClient {

  private final PersonRepository repository;

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

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

以下部分详细解释了每个步骤:

The sections that follow explain each step in detail: