查询方法
标准的 CRUD 功能仓库通常会对底层数据存储进行查询。使用 Spring Data 时,声明这些查询可以分为四个步骤:
-
声明一个接口,扩展
Repository
或其子接口,并将其类型指定为它应处理的域类和 ID 类型,如下例所示:interface PersonRepository extends Repository<Person, Long> { … }
-
在接口上声明查询方法。
interface PersonRepository extends Repository<Person, Long> {
List<Person> findByLastname(String lastname);
} -
使用 JavaConfig 或 XML 配置 设置 Spring 为这些接口创建代理实例。
- Java
- XML
import org.springframework.data.….repository.config.EnableNeo4jRepositories;
@EnableNeo4jRepositories
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
替换为例如mongodb
。请注意,JavaConfig 变体没有显式配置包,因为默认使用带注解类的包。要自定义要扫描的包,请使用数据存储特定的存储库的
@EnableNeo4jRepositories
注解的basePackage…
属性之一。 -
注入存储库实例并使用它,如下例所示:
class SomeClient {
private final PersonRepository repository;
SomeClient(PersonRepository repository) {
this.repository = repository;
}
void doSomething() {
List<Person> persons = repository.findByLastname("Matthews");
}
}
接下来的章节将详细解释每个步骤: