Search in sources :

Example 96 with Persistent

use of org.apache.cayenne.Persistent in project cayenne by apache.

the class CacheInvalidationFilter method preCommit.

/**
 * A callback method that records cache group to flush at the end of the commit.
 */
@PrePersist
@PreRemove
@PreUpdate
protected void preCommit(Object object) {
    // TODO: for some reason we can't use Persistent as the argument type... (is it fixed in Cayenne 4.0.M4?)
    Persistent p = (Persistent) object;
    Function<Persistent, Collection<CacheGroupDescriptor>> invalidationFunction = mappedHandlers.computeIfAbsent(p.getClass(), cl -> {
        for (InvalidationHandler handler : handlers) {
            Function<Persistent, Collection<CacheGroupDescriptor>> function = handler.canHandle(cl);
            if (function != null) {
                return function;
            }
        }
        return skipHandler;
    });
    Collection<CacheGroupDescriptor> objectGroups = invalidationFunction.apply(p);
    if (!objectGroups.isEmpty()) {
        getOrCreateTxGroups().addAll(objectGroups);
    }
}
Also used : Collection(java.util.Collection) Persistent(org.apache.cayenne.Persistent) PrePersist(org.apache.cayenne.annotation.PrePersist) PreRemove(org.apache.cayenne.annotation.PreRemove) PreUpdate(org.apache.cayenne.annotation.PreUpdate)

Example 97 with Persistent

use of org.apache.cayenne.Persistent in project cayenne by apache.

the class AshwoodEntitySorter method sortObjectsForEntity.

@SuppressWarnings("unchecked")
@Override
public void sortObjectsForEntity(ObjEntity objEntity, List<?> objects, boolean deleteOrder) {
    if (objects == null || objects.size() == 0) {
        return;
    }
    indexSorter();
    DbEntity dbEntity = objEntity.getDbEntity();
    // if no sorting is required
    if (!isReflexive(dbEntity)) {
        return;
    }
    Object probe = objects.get(0);
    if (probe instanceof DbRowOp) {
        sortObjectsForEntity(objEntity, (List<DbRowOp>) objects, deleteOrder, DbRowOp::getObject);
    } else if (probe instanceof Persistent) {
        sortObjectsForEntity(objEntity, (List<Persistent>) objects, deleteOrder, Function.identity());
    } else {
        throw new IllegalArgumentException("Can sort only Persistent or DbRow objects, got " + probe.getClass().getSimpleName());
    }
}
Also used : DbEntity(org.apache.cayenne.map.DbEntity) DbRowOp(org.apache.cayenne.access.flush.operation.DbRowOp) Persistent(org.apache.cayenne.Persistent) ArrayList(java.util.ArrayList) List(java.util.List)

Example 98 with Persistent

use of org.apache.cayenne.Persistent in project cayenne by apache.

the class AshwoodEntitySorter method buildDigraph.

protected <E> Digraph<E, Boolean> buildDigraph(ObjEntity objEntity, List<E> objects, Function<E, Persistent> converter) {
    EntityResolver resolver = converter.apply(objects.get(0)).getObjectContext().getEntityResolver();
    ClassDescriptor descriptor = resolver.getClassDescriptor(objEntity.getName());
    String[] reflexiveRelNames = getReflexiveRelationshipsNames(objEntity);
    int size = objects.size();
    Digraph<E, Boolean> objectDependencyGraph = new MapDigraph<>();
    Persistent[] masters = new Persistent[reflexiveRelNames.length];
    for (int i = 0; i < size; i++) {
        E current = objects.get(i);
        objectDependencyGraph.addVertex(current);
        int actualMasterCount = 0;
        for (int k = 0; k < reflexiveRelNames.length; k++) {
            String reflexiveRelName = reflexiveRelNames[k];
            if (reflexiveRelName == null) {
                continue;
            }
            Persistent persistent = converter.apply(current);
            masters[k] = (Persistent) descriptor.getProperty(reflexiveRelName).readProperty(persistent);
            if (masters[k] == null) {
                masters[k] = findReflexiveMaster(persistent, objEntity.getRelationship(reflexiveRelName), persistent.getObjectId().getEntityName());
            }
            if (masters[k] != null) {
                actualMasterCount++;
            }
        }
        int mastersFound = 0;
        for (int j = 0; j < size && mastersFound < actualMasterCount; j++) {
            if (i == j) {
                continue;
            }
            E masterCandidate = objects.get(j);
            for (Persistent master : masters) {
                if (converter.apply(masterCandidate) == master) {
                    objectDependencyGraph.putArc(masterCandidate, current, Boolean.TRUE);
                    mastersFound++;
                }
            }
        }
    }
    return objectDependencyGraph;
}
Also used : MapDigraph(org.apache.cayenne.ashwood.graph.MapDigraph) ClassDescriptor(org.apache.cayenne.reflect.ClassDescriptor) Persistent(org.apache.cayenne.Persistent) EntityResolver(org.apache.cayenne.map.EntityResolver)

Example 99 with Persistent

use of org.apache.cayenne.Persistent in project cayenne by apache.

the class DataContext method uncommittedObjects.

/**
 * Returns a collection of all uncommitted registered objects.
 *
 * @since 1.2
 */
@Override
public Collection<?> uncommittedObjects() {
    int len = getObjectStore().registeredObjectsCount();
    if (len == 0) {
        return Collections.EMPTY_LIST;
    }
    // guess target collection size
    Collection<Object> objects = new ArrayList<>(len > 100 ? len / 2 : len);
    Iterator it = getObjectStore().getObjectIterator();
    while (it.hasNext()) {
        Persistent object = (Persistent) it.next();
        int state = object.getPersistenceState();
        if (state == PersistenceState.MODIFIED || state == PersistenceState.NEW || state == PersistenceState.DELETED) {
            objects.add(object);
        }
    }
    return objects;
}
Also used : ArrayList(java.util.ArrayList) ResultIteratorIterator(org.apache.cayenne.util.ResultIteratorIterator) Iterator(java.util.Iterator) ResultIterator(org.apache.cayenne.ResultIterator) DataObject(org.apache.cayenne.DataObject) Persistent(org.apache.cayenne.Persistent)

Example 100 with Persistent

use of org.apache.cayenne.Persistent in project cayenne by apache.

the class DataContext method currentSnapshot.

/**
 * Returns a DataRow reflecting current, possibly uncommitted, object state.
 * <p>
 * <strong>Warning:</strong> This method will return a partial snapshot if
 * an object or one of its related objects that propagate their keys to this
 * object have temporary ids. DO NOT USE this method if you expect a DataRow
 * to represent a complete object state.
 * </p>
 *
 * @since 1.1
 */
public DataRow currentSnapshot(final Persistent object) {
    // for a HOLLOW object return snapshot from cache
    if (object.getPersistenceState() == PersistenceState.HOLLOW && object.getObjectContext() != null) {
        return getObjectStore().getSnapshot(object.getObjectId());
    }
    ObjEntity entity = getEntityResolver().getObjEntity(object);
    final ClassDescriptor descriptor = getEntityResolver().getClassDescriptor(entity.getName());
    final DataRow snapshot = new DataRow(10);
    snapshot.setEntityName(entity.getName());
    descriptor.visitProperties(new PropertyVisitor() {

        public boolean visitAttribute(AttributeProperty property) {
            ObjAttribute objAttr = property.getAttribute();
            // processing compound attributes correctly
            snapshot.put(objAttr.getDbAttributePath(), property.readPropertyDirectly(object));
            return true;
        }

        public boolean visitToMany(ToManyProperty property) {
            // do nothing
            return true;
        }

        public boolean visitToOne(ToOneProperty property) {
            ObjRelationship rel = property.getRelationship();
            // if target doesn't propagates its key value, skip it
            if (rel.isSourceIndependentFromTargetChange()) {
                return true;
            }
            Object targetObject = property.readPropertyDirectly(object);
            if (targetObject == null) {
                return true;
            }
            // to avoid unneeded fault triggering
            if (targetObject instanceof Fault) {
                DataRow storedSnapshot = getObjectStore().getSnapshot(object.getObjectId());
                if (storedSnapshot == null) {
                    throw new CayenneRuntimeException("No matching objects found for ObjectId %s" + ". Object may have been deleted externally.", object.getObjectId());
                }
                DbRelationship dbRel = rel.getDbRelationships().get(0);
                for (DbJoin join : dbRel.getJoins()) {
                    String key = join.getSourceName();
                    snapshot.put(key, storedSnapshot.get(key));
                }
                return true;
            }
            // target is resolved and we have an FK->PK to it,
            // so extract it from target...
            Persistent target = (Persistent) targetObject;
            Map<String, Object> idParts = target.getObjectId().getIdSnapshot();
            // this method.
            if (idParts.isEmpty()) {
                return true;
            }
            DbRelationship dbRel = rel.getDbRelationships().get(0);
            Map<String, Object> fk = dbRel.srcFkSnapshotWithTargetSnapshot(idParts);
            snapshot.putAll(fk);
            return true;
        }
    });
    // process object id map
    // we should ignore any object id values if a corresponding attribute
    // is a part of relationship "toMasterPK", since those values have been
    // set above when db relationships where processed.
    Map<String, Object> thisIdParts = object.getObjectId().getIdSnapshot();
    if (thisIdParts != null) {
        // put only those that do not exist in the map
        for (Map.Entry<String, Object> entry : thisIdParts.entrySet()) {
            String nextKey = entry.getKey();
            if (!snapshot.containsKey(nextKey)) {
                snapshot.put(nextKey, entry.getValue());
            }
        }
    }
    return snapshot;
}
Also used : ObjRelationship(org.apache.cayenne.map.ObjRelationship) ClassDescriptor(org.apache.cayenne.reflect.ClassDescriptor) ObjAttribute(org.apache.cayenne.map.ObjAttribute) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) Fault(org.apache.cayenne.Fault) Persistent(org.apache.cayenne.Persistent) AttributeProperty(org.apache.cayenne.reflect.AttributeProperty) DataRow(org.apache.cayenne.DataRow) ToOneProperty(org.apache.cayenne.reflect.ToOneProperty) ObjEntity(org.apache.cayenne.map.ObjEntity) ToManyProperty(org.apache.cayenne.reflect.ToManyProperty) DbRelationship(org.apache.cayenne.map.DbRelationship) DbJoin(org.apache.cayenne.map.DbJoin) DataObject(org.apache.cayenne.DataObject) Map(java.util.Map) PropertyVisitor(org.apache.cayenne.reflect.PropertyVisitor)

Aggregations

Persistent (org.apache.cayenne.Persistent)111 ObjectId (org.apache.cayenne.ObjectId)48 Test (org.junit.Test)40 ClassDescriptor (org.apache.cayenne.reflect.ClassDescriptor)20 ArrayList (java.util.ArrayList)18 CayenneRuntimeException (org.apache.cayenne.CayenneRuntimeException)17 Map (java.util.Map)13 DataObject (org.apache.cayenne.DataObject)13 ObjEntity (org.apache.cayenne.map.ObjEntity)12 AttributeProperty (org.apache.cayenne.reflect.AttributeProperty)12 HashMap (java.util.HashMap)11 EJBQLQuery (org.apache.cayenne.query.EJBQLQuery)10 PropertyVisitor (org.apache.cayenne.reflect.PropertyVisitor)9 ToManyProperty (org.apache.cayenne.reflect.ToManyProperty)9 ToOneProperty (org.apache.cayenne.reflect.ToOneProperty)9 DataRow (org.apache.cayenne.DataRow)8 Collection (java.util.Collection)7 DbAttribute (org.apache.cayenne.map.DbAttribute)7 ObjectContext (org.apache.cayenne.ObjectContext)6 DbEntity (org.apache.cayenne.map.DbEntity)6