How to map Json object to JPA specification for Search query

假如想象 提交于 2019-12-25 05:54:05

问题


I have a RequestMaping that get a Search json class as body params. I want to create proper Specification from this search json object so that pass to my Repository like this:

pagesResult = myRepository.findAll(mySpec)

I have problme with parsing and Dynamically add items to specification. I want to achieve something like this:

   @Override
    public Phones searchPhones(int pageNumber, Map<String, String> searchObject) {

        List<PhoneSpecification> specificationslist = new ArrayList<>();

        generateSpecifications(searchObject, specificationslist); //fill specificationList

        Specification<Phone> specificationOfPhone;
        for (PhoneSpecification spec :
                specificationslist) {

           //this is my problem , I had to dynamically increase my Specification like this:
            specificationOfPhone = specificationOfPhone + Specifications.and(spec);

        }

mobileRepository.findAll(specificationOfPhone);

回答1:


I finally achieve this by adding where to first specification and handle all by adding like this:

if(specificationslist.size()>0){
            finalSpecification = Specifications.where(specificationslist.get(0)) ;
        }

        for (int i=1 ; i<specificationslist.size(); i++) {
            finalSpecification = Specifications.where(finalSpecification).and(specificationslist.get(i));
        }



回答2:


You can change your code to this:

Specifications<Phone> specificationOfPhone = Specifications.where(null);
for (PhoneSpecification spec : specificationslist) {
    specificationOfPhone = specificationOfPhone.and(spec);
}

I assumed that PhoneSpecification is extending/implements Specification<T>.

Specifications.where(null); will return empty specification which can be chained with others.

Because Specifications<T> extends Specification<T> you can use it with your findAll method.



来源:https://stackoverflow.com/questions/42313944/how-to-map-json-object-to-jpa-specification-for-search-query

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