1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| package com.example.criteria;
import java.util.ArrayList; import java.util.List;
public class Criteria { private String field; private Object value; private Operator operator; private List<Criteria> chain;
private Criteria() { }
public static Criteria where(String field, Operator operator, Object value) { Criteria criteria = new Criteria(); criteria.field = field; criteria.operator = operator; criteria.value = value; return criteria; }
public Criteria and(Criteria criteria) { this.operator = Operator.AND; addCriteriaToChain(criteria); return this; }
public Criteria or(Criteria criteria) { this.operator = Operator.OR; addCriteriaToChain(criteria); return this; }
public Criteria eq(String field, Object value) { addCriteriaToChain(Criteria.where(field, Operator.EQUALS, value)); return this; }
public Criteria gt(String field, Object value) { addCriteriaToChain(Criteria.where(field, Operator.GREATER_THAN, value)); return this; }
private void addCriteriaToChain(Criteria criteria) { if (chain == null) { chain = new ArrayList<>(); } chain.add(criteria); }
public String build() { StringBuilder result = new StringBuilder();
if (chain != null) { result.append("(").append(field).append(" ").append(operator).append(" "); for (Criteria criteria : chain) { result.append(criteria.build()).append(" "); } result.append(")"); } else { result.append(field).append(" ").append(operator).append(" ").append(value); }
return result.toString(); }
public static void main(String[] args) { Criteria criteria = Criteria.where("age", Operator.GREATER_THAN, 18) .and(Criteria.where("gender", Operator.EQUALS, "female")) .or(Criteria.where("city", Operator.EQUALS, "New York")) .and(Criteria.where("score", Operator.GREATER_THAN, 90));
String query = criteria.build(); System.out.println("Query: " + query); }
public enum Operator { EQUALS("="), GREATER_THAN(">"), LESS_THAN("<"), AND("AND"), OR("OR");
private final String symbol;
Operator(String symbol) { this.symbol = symbol; }
@Override public String toString() { return symbol; } } }
|