2.6.3 Specification
我们可以定义Specification
来定制查询,我们需要Repository继承JpaSpecificationExecutor
接口;这样我们就可以在方法中使用Specification
参数了。
Specification
是函数接口,只有一个方法:
Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder);
root
:要查询的实体;query
:用来进行高级别的查询,如where
、select
方法等;criteriaBuilder
:用来构造查询,可使用如like
、equal
、lessThan
等,返回值为Predicate
;javax.persistence.criteria.Predicate
:用来作为查询的条件,可组合。
我们自定类来演示Specification
:
public class CustomSpecs {
public static Specification<Person> nameEqual(String name){
return (root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("name"), name); //1
}
public static Specification<Person> ageLessThanAndNameLike(Integer age, String name){
return (root, query, criteriaBuilder) -> {
Predicate ageLessThanPredicate = criteriaBuilder.lessThan(root.get("age"), age); //2
Predicate nameLikePredicate = criteriaBuilder.like(root.get("name"), "%" + name + "%"); //3
query.where(ageLessThanPredicate, nameLikePredicate); //4
return query.getRestriction(); //5
};
}
}
- 可用Lambda表达式来作为实现,使用
CriteriaBuilder
的equal
方法比较root.get("name")
和name
的相等性。 - 使用
lessThan
方法比较root.get("age")
是否比age
小; - 使用
like
方法比较root.get("name")
与"%" + name + "%"
; - 使用
CriteriaBuilder
的where
组合两个限制的Predicate
; - 获得
query
的组合的限制Predicate
。
我们验证一下:
...
import static top.wisely.learningspringdatajpa.domain.specification.CustomSpecs.*;
...
@Bean
CommandLineRunner specificationQuery(PersonRepository personRepository){
return args -> {
List<Person> people1 = personRepository.findAll(nameEqual("wyf")); //1
people1.forEach(System.out::println);
List<Person> people2 = personRepository.findAll(ageLessThanAndNameLike(37,"o"));
people2.forEach(System.out::println);
List<Person> people3 = personRepository.findAll(nameEqual("bar").or(ageLessThanAndNameLike(37, "o"))); //2
people3.forEach(System.out::println);
};
}
- 我们继承
JpaSpecificationExecutor
接口,获得了List<T> findAll(Specification<T> spec)
方法; - 可以用
Specification
的静态方法or
、and
等来连接多个Specification
。
新书推荐:
我的新书《从企业级开发到云原生微服务:Spring Boot 实战》已出版,内容涵盖了丰富Spring Boot开发的相关知识
购买地址:https://item.jd.com/12760084.html
主要包含目录有:
第一章 初识Spring Boot(快速领略Spring Boot的美丽)
第二章 开发必备工具(对常用开发工具进行介绍:包含IntelliJ IDEA、Gradle、Lombok、Docker等)
第三章 函数式编程
第四章 Spring 5.x基础(以Spring 5.2.x为基础)
第五章 深入Spring Boot(以Spring Boot 2.2.x为基础)
第六章 Spring Web MVC
第七章 数据访问(包含Spring Data JPA、Spring Data Elasticsearch和数据缓存)
第八章 安全控制(包含Spring Security和OAuth2)
第九章 响应式编程(包含Project Reactor、Spring WebFlux、Reactive NoSQL、R2DBC、Reactive Spring Security)
第十章 事件驱动(包含JMS、RabbitMQ、Kafka、Websocket、RSocket)
第11章 系统集成和屁股里(包含Spring Integration和Spring Batch)
第12章 Spring Cloud与微服务
第13章 Kubernetes与微服务(包含Kubernetes、Helm、Jenkins、Istio)
多谢大家支持。