Search in sources :

Example 66 with Persistent

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

the class DataContext method newObject.

/**
 * Instantiates a new object and registers it with this context. Object
 * class is determined from the mapped entity. Object class must have a
 * default constructor.
 * <p>
 * <i>Note: in most cases {@link #newObject(Class)} method should be used,
 * however this method is helpful when generic persistent classes are
 * used.</i>
 *
 * @since 3.0
 */
public Persistent newObject(String entityName) {
    ClassDescriptor descriptor = getEntityResolver().getClassDescriptor(entityName);
    if (descriptor == null) {
        throw new IllegalArgumentException("Invalid entity name: " + entityName);
    }
    Persistent object;
    try {
        object = (Persistent) descriptor.createObject();
    } catch (Exception ex) {
        throw new CayenneRuntimeException("Error instantiating object.", ex);
    }
    // this will initialize to-many lists
    descriptor.injectValueHolders(object);
    ObjectId id = new ObjectId(entityName);
    // note that the order of initialization of persistence artifacts below
    // is
    // important - do not change it lightly
    object.setObjectId(id);
    injectInitialValue(object);
    return object;
}
Also used : ClassDescriptor(org.apache.cayenne.reflect.ClassDescriptor) ObjectId(org.apache.cayenne.ObjectId) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) Persistent(org.apache.cayenne.Persistent) IOException(java.io.IOException) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException)

Example 67 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 68 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)

Example 69 with Persistent

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

the class DataContextMergeHandler method arcChanged.

// works the same for add and remove as long as we don't get too smart per TODO below.
private void arcChanged(Object nodeId, Object targetNodeId, Object arcId) {
    final Persistent source = (Persistent) context.getGraphManager().getNode(nodeId);
    if (source != null && source.getPersistenceState() != PersistenceState.HOLLOW) {
        final int state = source.getPersistenceState();
        PropertyDescriptor p = propertyForId(nodeId, arcId.toString());
        p.visit(new PropertyVisitor() {

            public boolean visitAttribute(AttributeProperty property) {
                return false;
            }

            public boolean visitToMany(ToManyProperty property) {
                if (state == PersistenceState.COMMITTED) {
                    property.invalidate(source);
                }
                return false;
            }

            public boolean visitToOne(ToOneProperty property) {
                if (state == PersistenceState.COMMITTED) {
                    property.invalidate(source);
                }
                // of dirty objects. See DataRowUtils for details.
                return false;
            }
        });
    }
}
Also used : PropertyDescriptor(org.apache.cayenne.reflect.PropertyDescriptor) ToManyProperty(org.apache.cayenne.reflect.ToManyProperty) Persistent(org.apache.cayenne.Persistent) AttributeProperty(org.apache.cayenne.reflect.AttributeProperty) PropertyVisitor(org.apache.cayenne.reflect.PropertyVisitor) ToOneProperty(org.apache.cayenne.reflect.ToOneProperty)

Example 70 with Persistent

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

the class DataDomainDeleteBucket method appendQueriesInternal.

@Override
void appendQueriesInternal(Collection<Query> queries) {
    DataNodeSyncQualifierDescriptor qualifierBuilder = new DataNodeSyncQualifierDescriptor();
    EntitySorter sorter = parent.getDomain().getEntitySorter();
    sorter.sortDbEntities(dbEntities, true);
    for (DbEntity dbEntity : dbEntities) {
        Collection<DbEntityClassDescriptor> descriptors = descriptorsByDbEntity.get(dbEntity);
        Map<Object, Query> batches = new LinkedHashMap<>();
        for (DbEntityClassDescriptor descriptor : descriptors) {
            qualifierBuilder.reset(descriptor);
            boolean isRootDbEntity = descriptor.isMaster();
            // remove object set for dependent entity, so that it does not show up
            // on post processing
            List<Persistent> objects = objectsByDescriptor.get(descriptor.getClassDescriptor());
            if (objects.isEmpty()) {
                continue;
            }
            checkReadOnly(descriptor.getEntity());
            if (isRootDbEntity) {
                sorter.sortObjectsForEntity(descriptor.getEntity(), objects, true);
            }
            for (Persistent o : objects) {
                ObjectDiff diff = parent.objectDiff(o.getObjectId());
                Map<String, Object> qualifierSnapshot = qualifierBuilder.createQualifierSnapshot(diff);
                // organize batches by the nulls in qualifier
                Set<String> nullQualifierNames = new HashSet<String>();
                for (Map.Entry<String, ?> entry : qualifierSnapshot.entrySet()) {
                    if (entry.getValue() == null) {
                        nullQualifierNames.add(entry.getKey());
                    }
                }
                Object batchKey = Arrays.asList(nullQualifierNames);
                DeleteBatchQuery batch = (DeleteBatchQuery) batches.get(batchKey);
                if (batch == null) {
                    batch = new DeleteBatchQuery(dbEntity, qualifierBuilder.getAttributes(), nullQualifierNames, 27);
                    batch.setUsingOptimisticLocking(qualifierBuilder.isUsingOptimisticLocking());
                    batches.put(batchKey, batch);
                }
                batch.add(qualifierSnapshot);
            }
        }
        queries.addAll(batches.values());
    }
}
Also used : EntitySorter(org.apache.cayenne.map.EntitySorter) DeleteBatchQuery(org.apache.cayenne.query.DeleteBatchQuery) Query(org.apache.cayenne.query.Query) DeleteBatchQuery(org.apache.cayenne.query.DeleteBatchQuery) Persistent(org.apache.cayenne.Persistent) LinkedHashMap(java.util.LinkedHashMap) DbEntity(org.apache.cayenne.map.DbEntity) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Aggregations

Persistent (org.apache.cayenne.Persistent)88 ObjectId (org.apache.cayenne.ObjectId)38 Test (org.junit.Test)32 ArrayList (java.util.ArrayList)17 CayenneRuntimeException (org.apache.cayenne.CayenneRuntimeException)17 ClassDescriptor (org.apache.cayenne.reflect.ClassDescriptor)17 DataObject (org.apache.cayenne.DataObject)13 Map (java.util.Map)12 ObjEntity (org.apache.cayenne.map.ObjEntity)10 EJBQLQuery (org.apache.cayenne.query.EJBQLQuery)10 AttributeProperty (org.apache.cayenne.reflect.AttributeProperty)10 DataRow (org.apache.cayenne.DataRow)8 PropertyVisitor (org.apache.cayenne.reflect.PropertyVisitor)8 ToManyProperty (org.apache.cayenne.reflect.ToManyProperty)8 ToOneProperty (org.apache.cayenne.reflect.ToOneProperty)8 Collection (java.util.Collection)7 HashMap (java.util.HashMap)7 ObjectContext (org.apache.cayenne.ObjectContext)6 DbEntity (org.apache.cayenne.map.DbEntity)6 List (java.util.List)5