Implement complex search feature using Spring BOOT

2020-07-29 23:42发布

问题:

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]

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.

based on the uri I need to build query using criteria api.

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?

Thanks in advance.

回答1:

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);
}

is corresponding to this request:

GET http://myhost/customers?registeredBefore=2015-01-18&lastName=Simpson

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.


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