1 19 20 package org.apache.cayenne.util; 21 22 import java.util.ArrayList ; 23 import java.util.Iterator ; 24 import java.util.List ; 25 26 import org.apache.cayenne.PersistenceState; 27 import org.apache.cayenne.Persistent; 28 import org.apache.cayenne.map.EntityResolver; 29 import org.apache.cayenne.map.ObjEntity; 30 import org.apache.cayenne.map.ObjRelationship; 31 import org.apache.cayenne.query.RelationshipQuery; 32 import org.apache.cayenne.reflect.Property; 33 34 40 public abstract class RelationshipFault { 41 42 protected Persistent relationshipOwner; 43 protected String relationshipName; 44 45 protected RelationshipFault() { 46 47 } 48 49 public RelationshipFault(Persistent relationshipOwner, String relationshipName) { 50 if (relationshipOwner == null) { 51 throw new NullPointerException ("'relationshipOwner' can't be null."); 52 } 53 54 if (relationshipName == null) { 55 throw new NullPointerException ("'relationshipName' can't be null."); 56 } 57 58 this.relationshipOwner = relationshipOwner; 59 this.relationshipName = relationshipName; 60 } 61 62 public String getRelationshipName() { 63 return relationshipName; 64 } 65 66 public Persistent getRelationshipOwner() { 67 return relationshipOwner; 68 } 69 70 protected boolean isTransientParent() { 71 int state = relationshipOwner.getPersistenceState(); 72 return state == PersistenceState.NEW || state == PersistenceState.TRANSIENT; 73 } 74 75 protected boolean isUncommittedParent() { 76 int state = relationshipOwner.getPersistenceState(); 77 return state == PersistenceState.MODIFIED || state == PersistenceState.DELETED; 78 } 79 80 84 protected List resolveFromDB() { 85 if (isTransientParent()) { 87 return new ArrayList (); 88 } 89 90 List resolved = relationshipOwner.getObjectContext().performQuery( 91 new RelationshipQuery( 92 relationshipOwner.getObjectId(), 93 relationshipName, 94 false)); 95 96 if (resolved.isEmpty()) { 97 return resolved; 98 } 99 100 102 EntityResolver resolver = relationshipOwner 103 .getObjectContext() 104 .getEntityResolver(); 105 ObjEntity sourceEntity = resolver.getObjEntity(relationshipOwner 106 .getObjectId() 107 .getEntityName()); 108 109 ObjRelationship relationship = (ObjRelationship) sourceEntity 110 .getRelationship(relationshipName); 111 ObjRelationship reverse = relationship.getReverseRelationship(); 112 113 if (reverse != null && !reverse.isToMany()) { 114 Property property = resolver.getClassDescriptor( 115 reverse.getSourceEntity().getName()).getProperty(reverse.getName()); 116 117 Iterator it = resolved.iterator(); 118 while (it.hasNext()) { 119 property.writePropertyDirectly(it.next(), null, relationshipOwner); 120 } 121 } 122 123 return resolved; 124 } 125 } 126 | Popular Tags |