Home > database >  how to get more clean code in java with mongoDB criteria query
how to get more clean code in java with mongoDB criteria query

Time:10-19

I am coding mongodb query in java

criteria.andOperator(Criteria.where("id").is(id),
         Criteria.where("name").is(name),
         Criteria.where("age").is(age),
         Criteria.where("address").is(address),
         Criteria.where("phonemun").is(phonenum));

I am coding the query as above.

criteria.andOperator(Criteria.where("id").is(id),
             Criteria.where("name").is(name));
if(age != null){
  criteria.andOperator(Criteria.where("age").is(age));
}
if(address != null){
  criteria.andOperator(Criteria.where("address").is(address));
}
if(phoneNum != null){
  criteria.andOperator(Criteria.where("phonenum").is(phoneNum));
}

This is the only method that comes to mind, but the more conditions, the more messy the code becomes. Is there a better way?

CodePudding user response:

You can try this:

Map<String, Object> params = new HashMap<>();
params.put("id", id);
params.put("name", name);
params.put("age", value);    // value is Integer or null
// ...similarly for phoneNum, address, etc

Collection<Criteria> criterias = new ArrayList<>();

params.forEach((k, v) -> {
    if (v != null) {
        criterias.add(Criteria.where(k).is(v));
    }
});

Criteria criteria = new Criteria().andOperator(criterias);

CodePudding user response:

If you had a method like addCriteria (Criteria crit, String fieldName, Object val)

if (val != null) {
    criteria.andOperator(Criteria.where(fieldName).is(val));
}

then you could put the logic in this method

addCriteria (criteria, "Age", age);
addCriteria (criteria, "Name", name);
  • Related