Search in sources :

Example 16 with ToManyProperty

use of org.apache.cayenne.reflect.ToManyProperty in project cayenne by apache.

the class Compiler method compileEntityResultWithPrefetch.

private EntityResult compileEntityResultWithPrefetch(EntityResult compiledResult, EJBQLExpression prefetchExpression) {
    final EntityResult result = compiledResult;
    String id = prefetchExpression.getText().toLowerCase();
    ClassDescriptor descriptor = descriptorsById.get(id);
    if (descriptor == null) {
        descriptor = descriptorsById.get(prefetchExpression.getText());
    }
    final String prefix = prefetchExpression.getText().substring(prefetchExpression.getText().indexOf(".") + 1);
    final Set<String> visited = new HashSet<String>();
    PropertyVisitor visitor = new PropertyVisitor() {

        public boolean visitAttribute(AttributeProperty property) {
            ObjAttribute oa = property.getAttribute();
            if (visited.add(oa.getDbAttributePath())) {
                result.addObjectField(oa.getEntity().getName(), "fetch." + prefix + "." + oa.getName(), prefix + "." + oa.getDbAttributeName());
            }
            return true;
        }

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

        public boolean visitToOne(ToOneProperty property) {
            ObjRelationship rel = property.getRelationship();
            DbRelationship dbRel = rel.getDbRelationships().get(0);
            for (DbJoin join : dbRel.getJoins()) {
                DbAttribute src = join.getSource();
                if (src.isForeignKey() && visited.add(src.getName())) {
                    result.addDbField("fetch." + prefix + "." + src.getName(), prefix + "." + src.getName());
                }
            }
            return true;
        }
    };
    descriptor.visitAllProperties(visitor);
    // append id columns ... (some may have been appended already via relationships)
    for (String pkName : descriptor.getEntity().getPrimaryKeyNames()) {
        if (visited.add(pkName)) {
            result.addDbField("fetch." + prefix + "." + pkName, prefix + "." + pkName);
        }
    }
    // append inheritance discriminator columns...
    for (ObjAttribute column : descriptor.getDiscriminatorColumns()) {
        if (visited.add(column.getName())) {
            result.addDbField("fetch." + prefix + "." + column.getDbAttributePath(), prefix + "." + column.getDbAttributePath());
        }
    }
    return result;
}
Also used : ObjRelationship(org.apache.cayenne.map.ObjRelationship) ClassDescriptor(org.apache.cayenne.reflect.ClassDescriptor) ObjAttribute(org.apache.cayenne.map.ObjAttribute) DbAttribute(org.apache.cayenne.map.DbAttribute) EntityResult(org.apache.cayenne.map.EntityResult) AttributeProperty(org.apache.cayenne.reflect.AttributeProperty) ToOneProperty(org.apache.cayenne.reflect.ToOneProperty) ToManyProperty(org.apache.cayenne.reflect.ToManyProperty) DbRelationship(org.apache.cayenne.map.DbRelationship) DbJoin(org.apache.cayenne.map.DbJoin) PropertyVisitor(org.apache.cayenne.reflect.PropertyVisitor) HashSet(java.util.HashSet)

Example 17 with ToManyProperty

use of org.apache.cayenne.reflect.ToManyProperty in project cayenne by apache.

the class Compiler method compileEntityResult.

private EntityResult compileEntityResult(EJBQLExpression expression, int position) {
    String id = expression.getText().toLowerCase();
    ClassDescriptor descriptor = descriptorsById.get(id);
    if (descriptor == null) {
        descriptor = descriptorsById.get(expression.getText());
    }
    if (descriptor == null) {
        throw new EJBQLException("the entity variable '" + id + "' does not refer to any entity in the FROM clause");
    }
    final EntityResult entityResult = new EntityResult(descriptor.getObjectClass());
    final String prefix = "ec" + position + "_";
    final int[] index = { 0 };
    final Set<String> visited = new HashSet<String>();
    PropertyVisitor visitor = new PropertyVisitor() {

        public boolean visitAttribute(AttributeProperty property) {
            ObjAttribute oa = property.getAttribute();
            if (visited.add(oa.getDbAttributePath())) {
                entityResult.addObjectField(oa.getEntity().getName(), oa.getName(), prefix + index[0]++);
            }
            return true;
        }

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

        public boolean visitToOne(ToOneProperty property) {
            ObjRelationship rel = property.getRelationship();
            DbRelationship dbRel = rel.getDbRelationships().get(0);
            for (DbJoin join : dbRel.getJoins()) {
                DbAttribute src = join.getSource();
                if (src.isForeignKey() && visited.add(src.getName())) {
                    entityResult.addDbField(src.getName(), prefix + index[0]++);
                }
            }
            return true;
        }
    };
    descriptor.visitAllProperties(visitor);
    // append id columns ... (some may have been appended already via relationships)
    for (String pkName : descriptor.getEntity().getPrimaryKeyNames()) {
        if (visited.add(pkName)) {
            entityResult.addDbField(pkName, prefix + index[0]++);
        }
    }
    // append inheritance discriminator columns...
    for (ObjAttribute column : descriptor.getDiscriminatorColumns()) {
        if (visited.add(column.getName())) {
            entityResult.addDbField(column.getDbAttributePath(), prefix + index[0]++);
        }
    }
    return entityResult;
}
Also used : ObjRelationship(org.apache.cayenne.map.ObjRelationship) ClassDescriptor(org.apache.cayenne.reflect.ClassDescriptor) ObjAttribute(org.apache.cayenne.map.ObjAttribute) EJBQLException(org.apache.cayenne.ejbql.EJBQLException) DbAttribute(org.apache.cayenne.map.DbAttribute) EntityResult(org.apache.cayenne.map.EntityResult) AttributeProperty(org.apache.cayenne.reflect.AttributeProperty) ToOneProperty(org.apache.cayenne.reflect.ToOneProperty) ToManyProperty(org.apache.cayenne.reflect.ToManyProperty) DbRelationship(org.apache.cayenne.map.DbRelationship) DbJoin(org.apache.cayenne.map.DbJoin) PropertyVisitor(org.apache.cayenne.reflect.PropertyVisitor) HashSet(java.util.HashSet)

Example 18 with ToManyProperty

use of org.apache.cayenne.reflect.ToManyProperty in project cayenne by apache.

the class SelectQueryMetadata method buildEntityResultForColumn.

/**
 * Collect metadata for column that will be unwrapped to full entity in the final SQL
 * (possibly including joint prefetch).
 * This information will be used to correctly create Persistent object back from raw result.
 *
 * This method is actually repeating logic of
 * {@link org.apache.cayenne.access.translator.select.DefaultSelectTranslator#appendQueryColumns}.
 * Here we don't care about intermediate joins and few other things so it's shorter.
 * Logic of these methods should be unified and simplified, possibly to a single source of metadata,
 * generated only once and used everywhere.
 *
 * @param query original query
 * @param column full object column
 * @param resolver entity resolver to get ObjEntity and ClassDescriptor
 * @return Entity result
 */
private EntityResult buildEntityResultForColumn(SelectQuery<?> query, Property<?> column, EntityResolver resolver) {
    final EntityResult result = new EntityResult(column.getType());
    // Collecting visitor for ObjAttributes and toOne relationships
    PropertyVisitor visitor = new PropertyVisitor() {

        public boolean visitAttribute(AttributeProperty property) {
            ObjAttribute oa = property.getAttribute();
            Iterator<CayenneMapEntry> dbPathIterator = oa.getDbPathIterator();
            while (dbPathIterator.hasNext()) {
                CayenneMapEntry pathPart = dbPathIterator.next();
                if (pathPart instanceof DbAttribute) {
                    result.addDbField(pathPart.getName(), pathPart.getName());
                }
            }
            return true;
        }

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

        public boolean visitToOne(ToOneProperty property) {
            DbRelationship dbRel = property.getRelationship().getDbRelationships().get(0);
            List<DbJoin> joins = dbRel.getJoins();
            for (DbJoin join : joins) {
                if (!join.getSource().isPrimaryKey()) {
                    result.addDbField(join.getSource().getName(), join.getSource().getName());
                }
            }
            return true;
        }
    };
    ObjEntity oe = resolver.getObjEntity(column.getType());
    DbEntity table = oe.getDbEntity();
    // Additionally collect PKs
    for (DbAttribute dba : table.getPrimaryKeys()) {
        result.addDbField(dba.getName(), dba.getName());
    }
    ClassDescriptor descriptor = resolver.getClassDescriptor(oe.getName());
    descriptor.visitAllProperties(visitor);
    // Collection columns for joint prefetch
    if (query.getPrefetchTree() != null) {
        for (PrefetchTreeNode prefetch : query.getPrefetchTree().adjacentJointNodes()) {
            // for each prefetch add columns from the target entity
            Expression prefetchExp = ExpressionFactory.exp(prefetch.getPath());
            ASTDbPath dbPrefetch = (ASTDbPath) oe.translateToDbPath(prefetchExp);
            DbRelationship r = findRelationByPath(table, dbPrefetch);
            if (r == null) {
                throw new CayenneRuntimeException("Invalid joint prefetch '%s' for entity: %s", prefetch, oe.getName());
            }
            // go via target OE to make sure that Java types are mapped correctly...
            ObjRelationship targetRel = (ObjRelationship) prefetchExp.evaluate(oe);
            ObjEntity targetEntity = targetRel.getTargetEntity();
            prefetch.setEntityName(targetRel.getSourceEntity().getName());
            String labelPrefix = dbPrefetch.getPath();
            Set<String> seenNames = new HashSet<>();
            for (ObjAttribute oa : targetEntity.getAttributes()) {
                Iterator<CayenneMapEntry> dbPathIterator = oa.getDbPathIterator();
                while (dbPathIterator.hasNext()) {
                    Object pathPart = dbPathIterator.next();
                    if (pathPart instanceof DbAttribute) {
                        DbAttribute attribute = (DbAttribute) pathPart;
                        if (seenNames.add(attribute.getName())) {
                            result.addDbField(labelPrefix + '.' + attribute.getName(), labelPrefix + '.' + attribute.getName());
                        }
                    }
                }
            }
            // append remaining target attributes such as keys
            DbEntity targetDbEntity = r.getTargetEntity();
            for (DbAttribute attribute : targetDbEntity.getAttributes()) {
                if (seenNames.add(attribute.getName())) {
                    result.addDbField(labelPrefix + '.' + attribute.getName(), labelPrefix + '.' + attribute.getName());
                }
            }
        }
    }
    return result;
}
Also used : ObjRelationship(org.apache.cayenne.map.ObjRelationship) ObjAttribute(org.apache.cayenne.map.ObjAttribute) ClassDescriptor(org.apache.cayenne.reflect.ClassDescriptor) ASTDbPath(org.apache.cayenne.exp.parser.ASTDbPath) DbAttribute(org.apache.cayenne.map.DbAttribute) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) EntityResult(org.apache.cayenne.map.EntityResult) AttributeProperty(org.apache.cayenne.reflect.AttributeProperty) ToOneProperty(org.apache.cayenne.reflect.ToOneProperty) CayenneMapEntry(org.apache.cayenne.util.CayenneMapEntry) ObjEntity(org.apache.cayenne.map.ObjEntity) ToManyProperty(org.apache.cayenne.reflect.ToManyProperty) DbEntity(org.apache.cayenne.map.DbEntity) Expression(org.apache.cayenne.exp.Expression) DbRelationship(org.apache.cayenne.map.DbRelationship) DbJoin(org.apache.cayenne.map.DbJoin) PropertyVisitor(org.apache.cayenne.reflect.PropertyVisitor) HashSet(java.util.HashSet)

Example 19 with ToManyProperty

use of org.apache.cayenne.reflect.ToManyProperty in project cayenne by apache.

the class DeepMergeOperation method merge.

private <T extends Persistent> T merge(final T peerInParentContext, ClassDescriptor descriptor, final Map<ObjectId, Persistent> seen) {
    ObjectId id = peerInParentContext.getObjectId();
    // sanity check
    if (id == null) {
        throw new CayenneRuntimeException("Server returned an object without an id: %s", peerInParentContext);
    }
    Persistent seenTarget = seen.get(id);
    if (seenTarget != null) {
        return (T) seenTarget;
    }
    final T target = shallowMergeOperation.merge(peerInParentContext);
    seen.put(id, target);
    descriptor = descriptor.getSubclassDescriptor(peerInParentContext.getClass());
    descriptor.visitProperties(new PropertyVisitor() {

        public boolean visitToOne(ToOneProperty property) {
            if (!property.isFault(peerInParentContext)) {
                Persistent destinationSource = (Persistent) property.readProperty(peerInParentContext);
                Object destinationTarget = destinationSource != null ? merge(destinationSource, property.getTargetDescriptor(), seen) : null;
                Object oldTarget = property.isFault(target) ? null : property.readProperty(target);
                property.writePropertyDirectly(target, oldTarget, destinationTarget);
            }
            return true;
        }

        public boolean visitToMany(ToManyProperty property) {
            if (!property.isFault(peerInParentContext)) {
                Object value = property.readProperty(peerInParentContext);
                Object targetValue;
                if (property instanceof ToManyMapProperty) {
                    Map<?, ?> map = (Map) value;
                    Map targetMap = new HashMap();
                    for (Entry entry : map.entrySet()) {
                        Object destinationSource = entry.getValue();
                        Object destinationTarget = destinationSource != null ? merge((Persistent) destinationSource, property.getTargetDescriptor(), seen) : null;
                        targetMap.put(entry.getKey(), destinationTarget);
                    }
                    targetValue = targetMap;
                } else {
                    Collection collection = (Collection) value;
                    Collection targetCollection = new ArrayList(collection.size());
                    for (Object destinationSource : collection) {
                        Object destinationTarget = destinationSource != null ? merge((Persistent) destinationSource, property.getTargetDescriptor(), seen) : null;
                        targetCollection.add(destinationTarget);
                    }
                    targetValue = targetCollection;
                }
                property.writePropertyDirectly(target, null, targetValue);
            }
            return true;
        }

        public boolean visitAttribute(AttributeProperty property) {
            return true;
        }
    });
    return target;
}
Also used : ObjectId(org.apache.cayenne.ObjectId) HashMap(java.util.HashMap) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) ArrayList(java.util.ArrayList) ToManyMapProperty(org.apache.cayenne.reflect.ToManyMapProperty) Persistent(org.apache.cayenne.Persistent) AttributeProperty(org.apache.cayenne.reflect.AttributeProperty) ToOneProperty(org.apache.cayenne.reflect.ToOneProperty) Entry(java.util.Map.Entry) ToManyProperty(org.apache.cayenne.reflect.ToManyProperty) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) PropertyVisitor(org.apache.cayenne.reflect.PropertyVisitor)

Example 20 with ToManyProperty

use of org.apache.cayenne.reflect.ToManyProperty in project cayenne by apache.

the class Util method unsetReverse.

static void unsetReverse(final Persistent sourceObject, String propertyName, final Persistent targetObject) {
    ArcProperty property = (ArcProperty) Cayenne.getClassDescriptor(sourceObject).getProperty(propertyName);
    ArcProperty reverseArc = property.getComplimentaryReverseArc();
    if (reverseArc != null) {
        reverseArc.visit(new PropertyVisitor() {

            public boolean visitToMany(ToManyProperty property) {
                property.removeTargetDirectly(targetObject, sourceObject);
                return false;
            }

            public boolean visitToOne(ToOneProperty property) {
                property.setTarget(targetObject, null, false);
                return false;
            }

            public boolean visitAttribute(AttributeProperty property) {
                return false;
            }
        });
        sourceObject.getObjectContext().getGraphManager().arcDeleted(targetObject.getObjectId(), sourceObject.getObjectId(), reverseArc.getName());
        markAsDirty(targetObject);
    }
}
Also used : ArcProperty(org.apache.cayenne.reflect.ArcProperty) ToManyProperty(org.apache.cayenne.reflect.ToManyProperty) AttributeProperty(org.apache.cayenne.reflect.AttributeProperty) PropertyVisitor(org.apache.cayenne.reflect.PropertyVisitor) ToOneProperty(org.apache.cayenne.reflect.ToOneProperty)

Aggregations

ToManyProperty (org.apache.cayenne.reflect.ToManyProperty)31 ToOneProperty (org.apache.cayenne.reflect.ToOneProperty)29 AttributeProperty (org.apache.cayenne.reflect.AttributeProperty)28 PropertyVisitor (org.apache.cayenne.reflect.PropertyVisitor)28 ClassDescriptor (org.apache.cayenne.reflect.ClassDescriptor)21 ArcProperty (org.apache.cayenne.reflect.ArcProperty)13 ObjRelationship (org.apache.cayenne.map.ObjRelationship)9 Persistent (org.apache.cayenne.Persistent)8 DbRelationship (org.apache.cayenne.map.DbRelationship)8 ObjAttribute (org.apache.cayenne.map.ObjAttribute)8 PropertyDescriptor (org.apache.cayenne.reflect.PropertyDescriptor)8 CayenneRuntimeException (org.apache.cayenne.CayenneRuntimeException)7 DbJoin (org.apache.cayenne.map.DbJoin)7 ObjEntity (org.apache.cayenne.map.ObjEntity)7 ObjectId (org.apache.cayenne.ObjectId)6 DbAttribute (org.apache.cayenne.map.DbAttribute)6 HashSet (java.util.HashSet)4 Map (java.util.Map)4 ArrayList (java.util.ArrayList)3 Collection (java.util.Collection)3