1 19 package org.apache.cayenne.intercept; 20 21 import java.util.Collection ; 22 import java.util.Iterator ; 23 24 import org.apache.cayenne.DeleteDenyException; 25 import org.apache.cayenne.LifecycleListener; 26 import org.apache.cayenne.ObjectContext; 27 import org.apache.cayenne.PersistenceState; 28 import org.apache.cayenne.Persistent; 29 import org.apache.cayenne.map.DeleteRule; 30 import org.apache.cayenne.map.ObjEntity; 31 import org.apache.cayenne.map.ObjRelationship; 32 import org.apache.cayenne.reflect.ClassDescriptor; 33 import org.apache.cayenne.reflect.LifecycleCallbackRegistry; 34 35 46 public class ObjectContextCallbackInterceptor extends ObjectContextDecorator { 47 48 protected LifecycleCallbackRegistry callbackRegistry; 49 50 public void setContext(ObjectContext context) { 51 super.setContext(context); 52 53 callbackRegistry = (context != null) ? context 54 .getEntityResolver() 55 .getCallbackRegistry() : null; 56 } 57 58 61 public Persistent newObject(Class persistentClass) { 62 Persistent object = super.newObject(persistentClass); 63 callbackRegistry.performCallbacks(LifecycleListener.PRE_PERSIST, object); 64 return object; 65 } 66 67 70 public void registerNewObject(Object object) { 71 super.registerNewObject(object); 72 callbackRegistry.performCallbacks(LifecycleListener.PRE_PERSIST, object); 73 } 74 75 79 public void deleteObject(Persistent object) throws DeleteDenyException { 80 applyPreRemoveCallbacks(object); 81 super.deleteObject(object); 82 } 83 84 88 void applyPreRemoveCallbacks(Persistent object) { 89 90 if (object.getPersistenceState() != PersistenceState.NEW) { 91 callbackRegistry.performCallbacks(LifecycleListener.PRE_REMOVE, object); 92 } 93 94 ObjEntity entity = getEntityResolver().lookupObjEntity(object); 95 ClassDescriptor descriptor = getEntityResolver().getClassDescriptor( 96 entity.getName()); 97 98 Iterator it = entity.getRelationships().iterator(); 99 while (it.hasNext()) { 100 101 ObjRelationship relationship = (ObjRelationship) it.next(); 102 if (relationship.getDeleteRule() == DeleteRule.CASCADE) { 103 104 Object related = descriptor 105 .getProperty(relationship.getName()) 106 .readProperty(object); 107 108 if (related == null) { 109 } 111 else if (related instanceof Collection ) { 112 Iterator relatedObjects = ((Collection ) related).iterator(); 113 while (relatedObjects.hasNext()) { 114 applyPreRemoveCallbacks((Persistent) relatedObjects.next()); 115 } 116 } 117 else { 118 applyPreRemoveCallbacks((Persistent) related); 119 } 120 } 121 } 122 } 123 } 124 | Popular Tags |