Implement complex search feature using Spring BOOT REST and Spring Data JPA using Criteria API

心已入冬 提交于 2019-12-06 14:46: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



来源:https://stackoverflow.com/questions/50645831/implement-complex-search-feature-using-spring-boot-rest-and-spring-data-jpa-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!