1 19 20 package org.apache.cayenne.access; 21 22 import java.util.List ; 23 24 import org.apache.cayenne.CayenneRuntimeException; 25 import org.apache.cayenne.Fault; 26 import org.apache.cayenne.ObjectContext; 27 import org.apache.cayenne.PersistenceState; 28 import org.apache.cayenne.Persistent; 29 import org.apache.cayenne.query.RelationshipQuery; 30 31 37 class DataContextFaults { 38 39 42 static void init() { 43 ToManyFault.init(); 44 ToOneFault.init(); 45 } 46 47 final static class ToManyFault extends Fault { 48 49 52 static void init() { 53 if (Fault.toManyFault == null) { 54 Fault.toManyFault = new ToManyFault(); 55 } 56 } 57 58 61 public Object resolveFault(Persistent sourceObject, String relationshipName) { 62 return new ToManyList(sourceObject, relationshipName); 63 } 64 } 65 66 final static class ToOneFault extends Fault { 67 68 71 static void init() { 72 if (Fault.toOneFault == null) { 73 Fault.toOneFault = new ToOneFault(); 74 } 75 } 76 77 80 public Object resolveFault(Persistent sourceObject, String relationshipName) { 81 int state = sourceObject.getPersistenceState(); 82 if(state == PersistenceState.NEW) { 83 return null; 84 } 85 86 Object target = doResolveFault(sourceObject, relationshipName); 87 88 90 ObjectContext context = sourceObject.getObjectContext(); 91 if ((state == PersistenceState.MODIFIED || state == PersistenceState.DELETED) 92 && context instanceof DataContext) { 93 94 ObjectDiff diff = (ObjectDiff) ((DataContext) context) 95 .getObjectStore() 96 .getChangesByObjectId() 97 .get(sourceObject.getObjectId()); 98 99 if (diff != null) { 100 diff.updateArcSnapshot(relationshipName, (Persistent) target); 101 } 102 } 103 104 return target; 105 } 106 107 Object doResolveFault(Persistent sourceObject, String relationshipName) { 108 RelationshipQuery query = new RelationshipQuery( 109 sourceObject.getObjectId(), 110 relationshipName, 111 false); 112 113 List objects = sourceObject.getObjectContext().performQuery(query); 114 115 if (objects.isEmpty()) { 116 return null; 117 } 118 else if (objects.size() == 1) { 119 return objects.get(0); 120 } 121 else { 122 throw new CayenneRuntimeException("Error resolving to-one fault. " 123 + "More than one object found. " 124 + "Source Id: " 125 + sourceObject.getObjectId() 126 + ", relationship: " 127 + relationshipName); 128 } 129 } 130 } 131 } 132 | Popular Tags |