1 19 20 package org.apache.cayenne.dataview; 21 22 import java.util.ArrayList ; 23 import java.util.List ; 24 25 import org.apache.cayenne.exp.Expression; 26 import org.apache.cayenne.exp.ExpressionFactory; 27 import org.apache.cayenne.query.SelectQuery; 28 29 public class BasicQueryBuilder { 30 31 private ObjEntityView queryTarget; 32 private List conditions = new ArrayList (); 33 34 public BasicQueryBuilder(ObjEntityView queryTarget) { 35 this.queryTarget = queryTarget; 36 } 37 38 public void addEqual(String fieldName, Object value) { 39 ObjEntityViewField field = queryTarget.getField(fieldName); 40 String path = null; 41 if (field.getCalcType().getValue() == CalcTypeEnum.NO_CALC_TYPE_VALUE) { 42 path = field.getObjAttribute().getName(); 43 } 44 else if (field.isLookup()) { 45 path = field.getObjRelationship().getName(); 46 } 47 Object rawValue = field.toRawValue(value); 48 conditions.add(ExpressionFactory.matchExp(path, rawValue)); 49 } 50 51 public void addRange(String fieldName, Object start, Object end) { 52 ObjEntityViewField field = queryTarget.getField(fieldName); 53 String path = null; 54 if (field.getCalcType().getValue() == CalcTypeEnum.NO_CALC_TYPE_VALUE) { 55 path = field.getObjAttribute().getName(); 56 } 57 else if (field.isLookup()) { 58 path = field.getObjRelationship().getName(); 59 } 60 Object rawStart = field.toRawValue(start); 61 Object rawEnd = field.toRawValue(end); 62 Expression expr = null; 63 if (rawStart != null && rawEnd != null) 64 expr = ExpressionFactory.betweenExp(path, rawStart, rawEnd); 65 else if (rawStart != null) 66 expr = ExpressionFactory.greaterOrEqualExp(path, rawStart); 67 else if (rawEnd != null) 68 expr = ExpressionFactory.lessOrEqualExp(path, rawEnd); 69 70 if (expr != null) 71 conditions.add(expr); 72 } 73 74 public void addLike(String fieldName, Object value, boolean caseSensetive) { 75 ObjEntityViewField field = queryTarget.getField(fieldName); 76 String path = null; 77 if (field.getCalcType().getValue() == CalcTypeEnum.NO_CALC_TYPE_VALUE) { 78 path = field.getObjAttribute().getName(); 79 } 80 else if (field.isLookup()) { 81 path = field.getObjRelationship().getName(); 82 } 83 Object rawValue = field.toRawValue(value); 84 String pattern = (rawValue != null ? rawValue.toString() : ""); 85 Expression expr = (caseSensetive 86 ? ExpressionFactory.likeExp(path, pattern) 87 : ExpressionFactory.likeIgnoreCaseExp(path, pattern)); 88 conditions.add(expr); 89 } 90 91 public SelectQuery getSelectQuery() { 92 SelectQuery query = new SelectQuery(queryTarget.getObjEntity()); 93 if (!conditions.isEmpty()) { 94 Expression qualifier = ExpressionFactory.joinExp(Expression.AND, conditions); 95 query.setQualifier(qualifier); 96 } 97 return query; 98 } 99 } 100 | Popular Tags |