简体   繁体   中英

How to create embedded predicate using QueryDSL, Spring-Data, MongoDB in Java

My repository implements the following interface:

QueryDslPredicateExecutor<Rule>

The structure of mongo's document(Rule object) is:

{
        "_id" : ObjectId("5aa924242a73bec4ce581717"),
        "name" : "test-name",
        "expressionGroups" : [
                {
                        "type" : "WHEN",
                        "expressions" : [
                                {
                                        "name" : "name1",
                                        "values" : ["VAL1", "VAL2", "VAL3"]
                                },
                                {
                                        "name" : "name2",
                                        "values" : ["VAL4", "VAL5"]
                                }
                        ]
                },
                {
                        "type" : "FOR",
                        "expressions" : [
                                {
                                        "name" : "name3",
                                        "values" : ["VAL6", "VAL7"]
                                }
                        ]
                }
        ]
}

I want to use the following method to find particular rule within mongodb:

Iterable<T> findAll(Predicate predicate);

I've prepared mongo shell query:

db.rule.find({
  'expressionGroups.expressions': {
    $all: [
      {
        '$elemMatch': {
          'name': "name1",
          'values': "VAL2"
        }
      },
      {
        '$elemMatch': {
          'name': "name3",
          'values': "VAL7"
        }
      }
    ]
  }
}).pretty()

How can I create com.querydsl.core.types.Predicate based on above query?

There is still no answer and I've met the same issue. So I created such code:

private List<Predicate> toPredicates(String root, Map<String, Object> map) {
    List<Predicate> predicates = new ArrayList<>();

    for (Map.Entry<String, Object> entry: map.entrySet()) {
        String path = root+'.'+entry.getKey();
        Object value = entry.getValue();

        if (entry.getValue() instanceof Map) {
            predicates.addAll(toPredicates(path, (Map<String, Object>) value));
        } else {
            predicates.add(new SimplePath(path).eq(value.toString()));
        }
    }

    return predicates;
}

private static class SimplePath extends StringPath {
    protected SimplePath(String var) {
        super(var);
    }
}

So, you can parse Json to Map and this is it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM