1 56 package org.objectstyle.cayenne.access.util; 57 58 import java.util.Iterator ; 59 import java.util.List ; 60 import java.util.ListIterator ; 61 62 import org.objectstyle.cayenne.CayenneRuntimeException; 63 import org.objectstyle.cayenne.DataObject; 64 import org.objectstyle.cayenne.ObjectId; 65 import org.objectstyle.cayenne.access.QueryEngine; 66 import org.objectstyle.cayenne.exp.Expression; 67 import org.objectstyle.cayenne.exp.ExpressionFactory; 68 import org.objectstyle.cayenne.map.DbRelationship; 69 import org.objectstyle.cayenne.map.ObjEntity; 70 import org.objectstyle.cayenne.map.ObjRelationship; 71 import org.objectstyle.cayenne.query.SelectQuery; 72 73 80 public class QueryUtils { 81 82 86 public static SelectQuery selectObjectForId(ObjectId oid) { 87 return new SelectQuery(oid.getObjectClass(), ExpressionFactory.matchAllDbExp(oid 88 .getIdSnapshot(), Expression.EQUAL_TO)); 89 } 90 91 95 public static SelectQuery selectQueryForIds(List oids) { 96 if (oids == null || oids.size() == 0) { 97 throw new IllegalArgumentException ("List must contain at least one ObjectId"); 98 } 99 100 SelectQuery sel = new SelectQuery(); 101 sel.setRoot(((ObjectId) oids.get(0)).getObjectClass()); 102 103 Iterator it = oids.iterator(); 104 105 ObjectId firstId = (ObjectId) it.next(); 106 Expression exp = ExpressionFactory.matchAllDbExp(firstId.getIdSnapshot(), 107 Expression.EQUAL_TO); 108 109 while (it.hasNext()) { 110 ObjectId anId = (ObjectId) it.next(); 111 exp = exp.orExp(ExpressionFactory.matchAllDbExp(anId.getIdSnapshot(), 112 Expression.EQUAL_TO)); 113 } 114 115 sel.setQualifier(exp); 116 return sel; 117 } 118 119 125 public static SelectQuery selectRelationshipObjects( 126 QueryEngine e, 127 DataObject source, 128 String relName) { 129 130 ObjEntity ent = e.getEntityResolver().lookupObjEntity(source); 131 ObjRelationship rel = (ObjRelationship) ent.getRelationship(relName); 132 ObjEntity destEnt = (ObjEntity) rel.getTargetEntity(); 133 134 List dbRels = rel.getDbRelationships(); 135 136 if (dbRels == null || dbRels.size() == 0) { 138 throw new CayenneRuntimeException("ObjRelationship '" 139 + rel.getName() 140 + "' is unmapped."); 141 } 142 143 StringBuffer buf = new StringBuffer (); 147 ListIterator it = dbRels.listIterator(dbRels.size()); 148 while (it.hasPrevious()) { 149 if (buf.length() > 0) { 150 buf.append("."); 151 } 152 DbRelationship dbRel = (DbRelationship) it.previous(); 153 DbRelationship reverse = dbRel.getReverseRelationship(); 154 155 if (reverse == null) { 157 throw new CayenneRuntimeException("DbRelationship '" 158 + dbRel.getName() 159 + "' has no reverse relationship"); 160 } 161 162 buf.append(reverse.getName()); 163 } 164 165 SelectQuery select = new SelectQuery(destEnt); 166 select.setQualifier(ExpressionFactory.matchDbExp(buf.toString(), source)); 167 select.setResolvingInherited(true); 169 return select; 170 } 171 } | Popular Tags |