查询方法
标准的 CRUD 功能 Repository 通常需要对底层数据存储执行查询。使用 Spring Data,声明这些查询分为四个步骤:
-
声明一个扩展 Repository 或其子接口之一的接口,并将其类型与应处理的领域类和 ID 类型关联起来,如下例所示:
interface PersonRepository extends Repository<Person, Long> { … }
-
在接口上声明查询方法。
interface PersonRepository extends Repository<Person, Long> { List<Person> findByLastname(String lastname); }
-
配置 Spring 以创建这些接口的代理实例,可以使用 JavaConfig 或 XML 配置。
-
Java
-
XML
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 命名空间。如果你将 Repository 抽象用于任何其他存储,你需要将其更改为你存储模块中相应的命名空间声明。换句话说,你应该将
jpa
替换为例如mongodb
。请注意,JavaConfig 变体没有显式配置包,因为默认使用注解类的包。要自定义扫描的包,请使用数据存储特定 Repository 的
@EnableJpaRepositories
注解中的basePackage…
属性之一。 -
-
注入 Repository 实例并使用它,如下例所示:
class SomeClient { private final PersonRepository repository; SomeClient(PersonRepository repository) { this.repository = repository; } void doSomething() { List<Person> persons = repository.findByLastname("Matthews"); } }
以下各节详细解释每个步骤。