使用Criteria API使用Spring BOOT REST和Spring Data JPA实现复杂的搜索功能
我需要使用Criteria API使用 Spring Boot REST 和 Spring Data JPA 实现复杂的搜索功能。我需要提供低于 / college的RPI?select = *& where = name:DemoCollege
和 location:LA
和 staff {firstName:foo,lastName:boo,workExp> 10}
并输入 [1,2,3]
I need to implement complex search feature using Spring Boot REST and Spring Data JPA using Criteria API. I need to provide RPIs like below
/college?select=*&where=name:DemoCollege
and location:LA
and staff{firstName:foo, lastName:boo, workExp>10}
and type in [1,2,3]
拼贴对象具有名称
,位置
,类型
字段和人员
列表。
它与 Staff
有 onetomany
关系,因此学院
可以有一个或多个职员。
Collage object has name
, location
, type
fields and staff
list.
It has onetomany
relationship with Staff
so College
can have one or many Staff members.
基于uri,我需要使用条件api建立查询。
based on the uri I need to build query using criteria api.
我发现实现 org.springframework.data.jpa.domain.Specification $ c的
toPredicate()
方法非常复杂$ c>。
I am finding it very complex to implement the toPredicate()
method of org.springframework.data.jpa.domain.Specification
. Is there any such example handing such complex search filters?
预先感谢。
在您的情况下,我认为最好的选择是 specification-arg-resolver lib,它提供了方便的方法来声明式地建立规范。例如,这段代码:
I think the best choice, in your case, is the specification-arg-resolver lib that provide convenient way to build specification declaratively. For example, this code:
@RequestMapping("/customers")
public Object findByName(
@And({
@Spec(path="registrationDate", params="registeredBefore", spec=DateBefore.class),
@Spec(path="lastName", spec=Like.class)}) Specification<Customer> customerSpec) {
return customerRepo.findAll(customerSpec);
}
与此请求相对应:
GET http://myhost/customers?registeredBefore=2015-01-18&lastName=Simpson
它支持以下规范:Like,LikeIgnoreCase,Equal,EqualIgnoreCase,In,Null,NotNull,GreaterThan,GreaterThanOrEqual,LessThan,LessThanOrEqual,DateBetween,Join,Join fetch及其
It supports the following specifications: Like, LikeIgnoreCase, Equal, EqualIgnoreCase, In, Null, NotNull, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, DateBetween, Join, Join fetch, and it allows you to combine them, composing complex expressions.
另一种选择是 Querydsl 和网络支持 Spring Data扩展。它还使您可以构建 REST查询语言,但可能性较小。您可以在我的答案中阅读如何使用它: https://stackoverflow.com/a/48596145
Another option is Querydsl and Web support Spring Data extensions. It also allows you to build a 'REST query language' but has fewer possibilities. You can read in my answer how to use it: https://stackoverflow.com/a/48596145