查询方法
标准的 CRUD 功能仓库通常对底层数据存储进行查询。使用 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 命名空间。如果您对任何其他存储使用仓库抽象,则需要将其更改为您的存储模块相应的命名空间声明。换句话说,您应该用例如
mongodb
来代替jpa
。请注意,JavaConfig 变体不显式配置包,因为默认使用带注解的类的包。要自定义要扫描的包,请使用特定数据存储仓库的
@EnableJpaRepositories
注解的basePackage…
属性之一。 -
-
注入仓库实例并使用它,如下例所示
class SomeClient { private final PersonRepository repository; SomeClient(PersonRepository repository) { this.repository = repository; } void doSomething() { List<Person> persons = repository.findByLastname("Matthews"); } }
以下各节详细解释了每个步骤