规约
JPA 的条件 API 让您能够以编程方式构建查询。Spring Data JPA Specification 提供了一个小巧而专注的 API,用于表达针对实体的谓词并在各仓库间复用。基于 Eric Evans《领域驱动设计》一书中的规约概念,规约遵循相同的语义,提供使用 JPA 定义条件的 API。要支持规约,您可以用 JpaSpecificationExecutor 接口扩展您的仓库接口,如下所示:
public interface CustomerRepository extends CrudRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
}
规约是使用条件 API 表达的、针对某个实体的谓词。Spring Data JPA 提供两个入口:
-
PredicateSpecification:随 Spring Data JPA 4.0 引入的一个灵活、与查询类型无关的接口。
-
Specification(以及
UpdateSpecification、DeleteSpecification):绑定到特定查询类型的变体。
PredicateSpecification 接口
PredicateSpecification 接口以最小的依赖集定义,从而支持广泛的函数式组合:
public interface PredicateSpecification<T> {
Predicate toPredicate(From<?, T> from, CriteriaBuilder builder);
}
规约可以很方便地用于构建一组可扩展的谓词集合并与 JpaRepository 配合使用,从而无需为每种所需的组合都声明一个查询(方法),如下例所示:
示例 1. 针对 Customer 的规约
class CustomerSpecs {
static PredicateSpecification<Customer> isLongTermCustomer() {
return (from, builder) -> {
LocalDate date = LocalDate.now().minusYears(2);
return builder.lessThan(from.get(Customer_.createdAt), date);
};
}
static PredicateSpecification<Customer> hasSalesOfMoreThan(MonetaryAmount value) {
return (from, builder) -> {
// build predicate for sales > value
};
}
}
Customer_ 类型是使用 JPA 元模型生成器生成的元模型类型(示例请参阅 Hibernate 实现的文档)。因此,表达式 Customer_.createdAt 假定 Customer 具有一个类型为 LocalDate 的 createdAt 属性。除此之外,我们已在业务需求抽象层面表达了一些条件,并创建了可执行的 Specification。
直接在仓库上使用规约:
List<Customer> customers = customerRepository.findAll(isLongTermCustomer());
规约在组合使用时最能体现其价值:
MonetaryAmount amount = new MonetaryAmount(200.0, Currencies.DOLLAR);
List<Customer> customers = customerRepository.findAll(
isLongTermCustomer().or(hasSalesOfMoreThan(amount))
);
Specification、UpdateSpecification 与 DeleteSpecification
Specification 接口早已存在,并受条件 API 限制而绑定到特定的查询类型(select、update、delete)。这三个规约接口定义如下:
- Specification
- UpdateSpecification
- DeleteSpecification
public interface Specification<T> {
Predicate toPredicate(Root<T> root, CriteriaQuery<?> query,
CriteriaBuilder builder);
}
public interface UpdateSpecification<T> {
Predicate toPredicate(Root<T> root, CriteriaUpdate<T> update,
CriteriaBuilder builder);
}
public interface DeleteSpecification<T> {
Predicate toPredicate(Root<T> root, CriteriaDelete<T> delete,
CriteriaBuilder builder);
}
Specification 对象既可以直接构造,也可以通过复用 PredicateSpecification 实例来构造,如下例所示:
示例 2. 针对 Customer 的规约
public class CustomerSpecs {
public static UpdateSpecification<Customer> updateLastnameByFirstnameAndLastname(String newLastName, String currentFirstname, String currentLastname) {
return UpdateSpecification.<Customer>update((root, update, criteriaBuilder) -> {
update.set("lastname", newLastName);
}).where(hasFirstname(currentFirstname).and(hasLastname(currentLastname)));
}
public static PredicateSpecification<Customer> hasFirstname(String firstname) {
return (root, builder) -> {
return builder.equal(root.get("firstname"), firstname);
};
}
public static PredicateSpecification<Customer> hasLastname(String lastname) {
return (root, builder) -> {
// build query here
};
}
}
流式 API
JpaSpecificationExecutor 定义了流式查询方法,用于基于 Specification 实例灵活地执行查询:
-
针对
PredicateSpecification:findBy(PredicateSpecification<T> spec, Function<? super SpecificationFluentQuery<S>, R> queryFunction) -
针对
Specification:findBy(Specification<T> spec, Function<? super SpecificationFluentQuery<S>, R> queryFunction)
与其他方法一样,它会执行一个从 Specification 派生出来的查询。不过,查询函数让您能够控制查询执行中那些原本无法动态控制的方面。您通过调用 SpecificationFluentQuery 的各种中间方法和终止方法来做到这一点。
中间方法
-
sortBy:为结果应用排序。重复调用会追加每个Sort(注意,使用带排序的Pageable调用page(Pageable)会覆盖此前的任何排序顺序)。 -
limit:限制结果数量。 -
as:指定要读取或投影到的类型。 -
project:限制查询的属性。
终止方法
-
first、firstValue:返回第一个值。如果查询未产生任何结果,first返回Optional<T>或Optional.empty()。firstValue是其可空变体,无需使用Optional。 -
one、oneValue:返回唯一的值。如果查询未产生任何结果,one返回Optional<T>或Optional.empty()。oneValue是其可空变体,无需使用Optional。如果找到多个匹配项,则抛出IncorrectResultSizeDataAccessException。 -
all:将所有结果作为List<T>返回。 -
page(Pageable):将所有结果作为Page<T>返回。 -
slice(Pageable):将所有结果作为Slice<T>返回。 -
scroll(ScrollPosition):使用滚动(偏移量、键集)将结果作为Window<T>检索。 -
stream():返回一个Stream<T>,以流的方式处理结果,而不是将其物化为Collection(请参阅流语义)。该流是有状态的,使用后必须关闭。 -
count和exists:返回匹配实体的数量,或是否存在任何匹配。
中间方法和终止方法必须在查询函数内调用。
示例 3. 使用流式 API 获取按 lastname 排序的投影 Page
Page<CustomerProjection> page = repository.findBy(spec,
q -> q.as(CustomerProjection.class)
.page(PageRequest.of(0, 20, Sort.by("lastname")))
);
示例 4. 使用流式 API 获取按 lastname 排序的潜在多条结果中的最后一条
Optional<Customer> match = repository.findBy(spec,
q -> q.sortBy(Sort.by("lastname").descending())
.first()
);