【发布时间】:2018-07-16 19:13:48
【问题描述】:
这里是 Spring Boot。当在实现复杂查询的上下文中使用时,我试图绕开JpaRepositories 和Specifications 并努力在几个项目上看到“树林中的森林”。
Specification 的典型示例如下:
public class PersonSpecification implements Specification<Person> {
private Person filter;
public PersonSpecification(Person filter) {
super();
this.filter = filter;
}
public Predicate toPredicate(Root<Person> root, CriteriaQuery<?> cq,
CriteriaBuilder cb) {
Predicate p = cb.disjunction();
if (filter.getName() != null) {
p.getExpressions()
.add(cb.equal(root.get("name"), filter.getName()));
}
if (filter.getSurname() != null && filter.getAge() != null) {
p.getExpressions().add(
cb.and(cb.equal(root.get("surname"), filter.getSurname()),
cb.equal(root.get("age"), filter.getAge())));
}
return p;
}
}
在这个toPredicate(...) 方法中,Root<Person> 和CriteriaQuery 代表什么?最重要的是,听起来您需要为要应用的每种类型的过滤器创建一个Specification impl,因为每个规范都会被翻译成一个且只有一个谓词...因此,例如,如果我想找到所有姓氏为“Smeeb”且年龄大于 25 岁的人,听起来我需要写一个 LastnameMatchingSpecification<Person> 和一个 AgeGreaterThanSpecification<Person>。有人可以为我确认或澄清这一点吗?!
【问题讨论】:
标签: spring-boot spring-data spring-data-jpa jpa-criteria