Spring 有一个围绕 JPA 标准 API(使用谓词)的包装器,称为规范 API。
编写规范时可以执行以下操作,为每个条件编写规范:
public static Specification<Car> withLicensePlate(String licensePlate) {
return (root, query, cb) -> licensePlate == null ? null : cb.equal(root.get("licensePlate"), licensePlate);
}
public static Specification<Car> withRating(String rating) {
return (root, query, cb) -> rating == null ? null : cb.equal(root.get("rating"), rating);
}
public static Specification<Car> withName(String name) {
return (root, query, cb) -> name == null ? null : cb.equal(root.get("name"), name);
}
它还允许您编写连接操作:
public static Specification<Car> withSeatType(String type) {
return (root, query, cb) -> {
return type == null ? null : cb.equal(root.join("interior", JoinType.LEFT).get("type"), type);
};
}
您可以返回null
在一个标准内,它允许您使这些规范成为“可选”。之后,您可以使用Specifications.where()
结合这些标准:
Specification<Car> spec = Specifications
.where(withLicensePlate(licensePlate))
.and(withRating(rating))
.and(withName(name))
.and(withSeatType(seatType));
如果您像我在本例中那样编写单独的规范,则可以在必要时重新使用它们。否则,您将不得不编写特定于操作的规范,而面试官也可能会发现这种规范无法扩展。
编写规范后,您必须从JpaSpecificationExecutor
界面并使用findAll(Specification)
method.