如何将Json对象映射到Search查询的JPA规范

时间:2017-02-18 10:29:52

标签: jpa dynamic specifications

我有一个RequestMaping,它将Search json类作为body params。 我想从这个搜索json对象创建适当的规范,以便像这样传递到我的存储库:

pagesResult = myRepository.findAll(mySpec)

我有解析和动态添加项目到规范的问题。我希望实现这样的目标:

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

2 个答案:

答案 0 :(得分:1)

您可以将代码更改为:

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

我认为PhoneSpecification正在扩展/实施Specification<T>

Specifications.where(null);将返回空的规范,可以与其他人链接。

由于Specifications<T>扩展Specification<T>,您可以将其与findAll方法一起使用。

答案 1 :(得分:1)

我最终通过添加第一个规范的位置来实现这一点,并通过这样添加来处理所有:

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