1 56 package org.objectstyle.cayenne; 57 58 import java.io.Serializable ; 59 import java.util.List ; 60 61 import org.objectstyle.cayenne.access.DataContext; 62 import org.objectstyle.cayenne.access.ToManyList; 63 import org.objectstyle.cayenne.conf.Configuration; 64 import org.objectstyle.cayenne.map.DbRelationship; 65 import org.objectstyle.cayenne.map.EntityResolver; 66 import org.objectstyle.cayenne.map.ObjEntity; 67 import org.objectstyle.cayenne.map.ObjRelationship; 68 import org.objectstyle.cayenne.query.RelationshipQuery; 69 70 79 80 public abstract class Fault implements Serializable { 83 84 protected static final Fault toOneFault = new ToOneFault(); 85 protected static final Fault toManyFault = new ToManyFault(); 86 87 public static Fault getToOneFault() { 88 return toOneFault; 89 } 90 91 public static Fault getToManyFault() { 92 return toManyFault; 93 } 94 95 protected Fault() { 96 } 97 98 101 public abstract Object resolveFault(DataObject sourceObject, String relationshipName); 102 103 final static class ToManyFault extends Fault { 104 105 108 public Object resolveFault(DataObject sourceObject, String relationshipName) { 109 return new ToManyList(sourceObject, relationshipName); 110 } 111 } 112 113 final static class ToOneFault extends Fault { 114 115 118 public Object resolveFault(DataObject sourceObject, String relationshipName) { 119 DataContext context = sourceObject.getDataContext(); 120 EntityResolver resolver = context.getEntityResolver(); 121 122 ObjEntity entity = resolver.lookupObjEntity(sourceObject); 123 ObjRelationship relationship = (ObjRelationship) entity 124 .getRelationship(relationshipName); 125 126 129 134 ObjEntity targetEntity = (ObjEntity) relationship.getTargetEntity(); 135 if (relationship.isSourceIndependentFromTargetChange()) { 136 137 139 RelationshipQuery query = new RelationshipQuery( 140 sourceObject, 141 relationship); 142 List objects = context.performQuery(query); 143 144 if (objects.isEmpty()) { 145 return null; 146 } 147 else if (objects.size() == 1) { 148 return objects.get(0); 149 } 150 else { 151 throw new CayenneRuntimeException("Error resolving to-one fault. " 152 + "More than one object found. " 153 + "Fault entity: " 154 + targetEntity.getName()); 155 } 156 } 157 158 DbRelationship dbRel = (DbRelationship) relationship 160 .getDbRelationships() 161 .get(0); 162 Class targetClass = targetEntity.getJavaClass(Configuration 163 .getResourceLoader()); 164 ObjectId id = context.getObjectStore().getSnapshot( 165 sourceObject.getObjectId(), 166 context).createTargetObjectId(targetClass, dbRel); 167 168 if (id == null) { 169 return null; 170 } 171 172 173 if (resolver.lookupInheritanceTree(targetEntity) != null) { 174 return DataObjectUtils.objectForPK(context, id); 176 } 177 else { 178 return context.registeredObject(id); 179 } 180 } 181 182 } 183 } | Popular Tags |