Search in sources :

Example 1 with ObjEntity

use of org.apache.cayenne.map.ObjEntity in project cayenne by apache.

the class DataDomainIndirectDiffBuilder method arcCreated.

@Override
public void arcCreated(Object nodeId, Object targetNodeId, Object arcId) {
    ObjEntity entity = resolver.getObjEntity(((ObjectId) nodeId).getEntityName());
    ObjRelationship relationship = entity.getRelationship(arcId.toString());
    if (relationship.isSourceIndependentFromTargetChange()) {
        ObjectId nodeObjectId = (ObjectId) nodeId;
        if (!nodeObjectId.isTemporary()) {
            indirectModifications.add(nodeObjectId);
        }
        if (relationship.isFlattened()) {
            if (relationship.isReadOnly()) {
                throw new CayenneRuntimeException("Cannot set the read-only flattened relationship '%s' in ObjEntity '%s'.", relationship.getName(), relationship.getSourceEntity().getName());
            }
            // Register this combination (so we can remove it later if an insert occurs before commit)
            FlattenedArcKey key = new FlattenedArcKey((ObjectId) nodeId, (ObjectId) targetNodeId, relationship);
            // If this combination has already been deleted, simply undelete it.
            if (!flattenedDeletes.remove(key)) {
                flattenedInserts.add(key);
            }
        }
    }
}
Also used : ObjEntity(org.apache.cayenne.map.ObjEntity) ObjRelationship(org.apache.cayenne.map.ObjRelationship) ObjectId(org.apache.cayenne.ObjectId) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException)

Example 2 with ObjEntity

use of org.apache.cayenne.map.ObjEntity in project cayenne by apache.

the class DiffProcessor method arcDeleted.

@Override
public void arcDeleted(Object nodeId, Object targetNodeId, Object arcId) {
    ObjectId id = (ObjectId) nodeId;
    String relationshipName = arcId.toString();
    ObjEntity entity = entityResolver.getObjEntity(id.getEntityName());
    ObjRelationship relationship = entity.getRelationship(relationshipName);
    MutableObjectChange c = changeSet.getOrCreate(id, ObjectChangeType.UPDATE);
    ObjectId tid = (ObjectId) targetNodeId;
    if (relationship.isToMany()) {
        c.toManyRelationshipDisconnected(relationshipName, tid);
    } else {
        c.toOneRelationshipDisconnected(relationshipName, tid);
    }
}
Also used : MutableObjectChange(org.apache.cayenne.commitlog.model.MutableObjectChange) ObjEntity(org.apache.cayenne.map.ObjEntity) ObjRelationship(org.apache.cayenne.map.ObjRelationship) ObjectId(org.apache.cayenne.ObjectId)

Example 3 with ObjEntity

use of org.apache.cayenne.map.ObjEntity in project cayenne by apache.

the class CodeGeneratorControllerBase method getItemName.

public JLabel getItemName(Object obj) {
    String className;
    Icon icon = null;
    if (obj instanceof Embeddable) {
        className = ((Embeddable) obj).getClassName();
        icon = CellRenderers.iconForObject(new Embeddable());
    } else {
        className = ((ObjEntity) obj).getName();
        icon = CellRenderers.iconForObject(new ObjEntity());
    }
    JLabel labelIcon = new JLabel();
    labelIcon.setIcon(icon);
    labelIcon.setVisible(true);
    labelIcon.setText(className);
    return labelIcon;
}
Also used : ObjEntity(org.apache.cayenne.map.ObjEntity) JLabel(javax.swing.JLabel) Icon(javax.swing.Icon) Embeddable(org.apache.cayenne.map.Embeddable)

Example 4 with ObjEntity

use of org.apache.cayenne.map.ObjEntity in project cayenne by apache.

the class DefaultSelectTranslator method appendQueryColumns.

/**
 * Appends columns needed for object SelectQuery to the provided columns
 * list.
 */
<T> List<ColumnDescriptor> appendQueryColumns(final List<ColumnDescriptor> columns, SelectQuery<T> query, ClassDescriptor descriptor, final String tableAlias) {
    final Set<ColumnTracker> attributes = new HashSet<>();
    // fetched attributes include attributes that are either:
    // 
    // * class properties
    // * PK
    // * FK used in relationship
    // * joined prefetch PK
    ObjEntity oe = descriptor.getEntity();
    PropertyVisitor visitor = new PropertyVisitor() {

        public boolean visitAttribute(AttributeProperty property) {
            ObjAttribute oa = property.getAttribute();
            resetJoinStack();
            Iterator<CayenneMapEntry> dbPathIterator = oa.getDbPathIterator();
            while (dbPathIterator.hasNext()) {
                Object pathPart = dbPathIterator.next();
                if (pathPart == null) {
                    throw new CayenneRuntimeException("ObjAttribute has no component: %s", oa.getName());
                } else if (pathPart instanceof DbRelationship) {
                    DbRelationship rel = (DbRelationship) pathPart;
                    dbRelationshipAdded(rel, JoinType.LEFT_OUTER, null);
                } else if (pathPart instanceof DbAttribute) {
                    DbAttribute dbAttr = (DbAttribute) pathPart;
                    appendColumn(columns, oa, dbAttr, attributes, null, tableAlias);
                }
            }
            return true;
        }

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

        public boolean visitToOne(ToOneProperty property) {
            visitRelationship(property);
            return true;
        }

        private void visitRelationship(ArcProperty property) {
            resetJoinStack();
            ObjRelationship rel = property.getRelationship();
            DbRelationship dbRel = rel.getDbRelationships().get(0);
            List<DbJoin> joins = dbRel.getJoins();
            for (DbJoin join : joins) {
                DbAttribute src = join.getSource();
                appendColumn(columns, null, src, attributes, null, tableAlias);
            }
        }
    };
    descriptor.visitAllProperties(visitor);
    // stack should be reset, because all root table attributes go with "t0"
    // table alias
    resetJoinStack();
    // add remaining needed attrs from DbEntity
    DbEntity table = oe.getDbEntity();
    for (DbAttribute dba : table.getPrimaryKeys()) {
        appendColumn(columns, null, dba, attributes, null, tableAlias);
    }
    if (query instanceof PrefetchSelectQuery) {
        // for each relationship path add PK of the target entity...
        for (String path : ((PrefetchSelectQuery) query).getResultPaths()) {
            ASTDbPath pathExp = (ASTDbPath) oe.translateToDbPath(ExpressionFactory.exp(path));
            // add joins and find terminating element
            resetJoinStack();
            PathComponent<DbAttribute, DbRelationship> lastComponent = null;
            for (PathComponent<DbAttribute, DbRelationship> component : table.resolvePath(pathExp, getPathAliases())) {
                if (component.getRelationship() != null) {
                    // do not invoke dbRelationshipAdded(), invoke
                    // pushJoin() instead. This is to prevent
                    // 'forcingDistinct' flipping to true, that will result
                    // in unneeded extra processing and sometimes in invalid
                    // results (see CAY-1979). Distinctness of each row is
                    // guaranteed by the prefetch query semantics - we
                    // include target ID in the result columns
                    getJoinStack().pushJoin(component.getRelationship(), component.getJoinType(), null);
                }
                lastComponent = component;
            }
            // process terminating element
            if (lastComponent != null) {
                DbRelationship relationship = lastComponent.getRelationship();
                if (relationship != null) {
                    String labelPrefix = pathExp.getPath();
                    DbEntity targetEntity = relationship.getTargetEntity();
                    for (DbAttribute pk : targetEntity.getPrimaryKeys()) {
                        // note that we my select a source attribute, but
                        // label it as
                        // target for simplified snapshot processing
                        appendColumn(columns, null, pk, attributes, labelPrefix + '.' + pk.getName());
                    }
                }
            }
        }
    }
    // handle joint prefetches directly attached to this query...
    if (query.getPrefetchTree() != null) {
        // perform some sort of union or sub-queries.
        for (PrefetchTreeNode prefetch : query.getPrefetchTree().getChildren()) {
            prefetch.setEntityName(oe.getName());
        }
        for (PrefetchTreeNode prefetch : query.getPrefetchTree().adjacentJointNodes()) {
            // for each prefetch add all joins plus columns from the target
            // entity
            Expression prefetchExp = ExpressionFactory.exp(prefetch.getPath());
            ASTDbPath dbPrefetch = (ASTDbPath) oe.translateToDbPath(prefetchExp);
            resetJoinStack();
            DbRelationship r = null;
            for (PathComponent<DbAttribute, DbRelationship> component : table.resolvePath(dbPrefetch, getPathAliases())) {
                r = component.getRelationship();
                dbRelationshipAdded(r, JoinType.LEFT_OUTER, null);
            }
            if (r == null) {
                throw new CayenneRuntimeException("Invalid joint prefetch '%s' for entity: %s", prefetch, oe.getName());
            }
            // add columns from the target entity, including those that are matched
            // against the FK of the source entity.
            // This is needed to determine whether optional relationships are null
            // go via target OE to make sure that Java types are mapped correctly...
            ObjRelationship targetRel = (ObjRelationship) prefetchExp.evaluate(oe);
            ObjEntity targetEntity = targetRel.getTargetEntity();
            String labelPrefix = dbPrefetch.getPath();
            PropertyVisitor prefetchVisitor = new PropertyVisitor() {

                public boolean visitAttribute(AttributeProperty property) {
                    ObjAttribute oa = property.getAttribute();
                    Iterator<CayenneMapEntry> dbPathIterator = oa.getDbPathIterator();
                    while (dbPathIterator.hasNext()) {
                        Object pathPart = dbPathIterator.next();
                        if (pathPart == null) {
                            throw new CayenneRuntimeException("ObjAttribute has no component: %s", oa.getName());
                        } else if (pathPart instanceof DbRelationship) {
                            DbRelationship rel = (DbRelationship) pathPart;
                            dbRelationshipAdded(rel, JoinType.INNER, null);
                        } else if (pathPart instanceof DbAttribute) {
                            DbAttribute dbAttr = (DbAttribute) pathPart;
                            appendColumn(columns, oa, dbAttr, attributes, labelPrefix + '.' + dbAttr.getName());
                        }
                    }
                    return true;
                }

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

                public boolean visitToOne(ToOneProperty property) {
                    return true;
                }
            };
            ClassDescriptor prefetchClassDescriptor = entityResolver.getClassDescriptor(targetEntity.getName());
            prefetchClassDescriptor.visitAllProperties(prefetchVisitor);
            // append remaining target attributes such as keys
            DbEntity targetDbEntity = r.getTargetEntity();
            for (DbAttribute attribute : targetDbEntity.getAttributes()) {
                appendColumn(columns, null, attribute, attributes, labelPrefix + '.' + attribute.getName());
            }
        }
    }
    return columns;
}
Also used : ArcProperty(org.apache.cayenne.reflect.ArcProperty) ObjAttribute(org.apache.cayenne.map.ObjAttribute) ASTDbPath(org.apache.cayenne.exp.parser.ASTDbPath) ClassDescriptor(org.apache.cayenne.reflect.ClassDescriptor) CayenneRuntimeException(org.apache.cayenne.CayenneRuntimeException) DbAttribute(org.apache.cayenne.map.DbAttribute) ToOneProperty(org.apache.cayenne.reflect.ToOneProperty) CayenneMapEntry(org.apache.cayenne.util.CayenneMapEntry) DbEntity(org.apache.cayenne.map.DbEntity) PrefetchTreeNode(org.apache.cayenne.query.PrefetchTreeNode) HashSet(java.util.HashSet) ObjRelationship(org.apache.cayenne.map.ObjRelationship) AttributeProperty(org.apache.cayenne.reflect.AttributeProperty) PrefetchSelectQuery(org.apache.cayenne.query.PrefetchSelectQuery) ObjEntity(org.apache.cayenne.map.ObjEntity) ToManyProperty(org.apache.cayenne.reflect.ToManyProperty) Expression(org.apache.cayenne.exp.Expression) DbRelationship(org.apache.cayenne.map.DbRelationship) DbJoin(org.apache.cayenne.map.DbJoin) PropertyVisitor(org.apache.cayenne.reflect.PropertyVisitor)

Example 5 with ObjEntity

use of org.apache.cayenne.map.ObjEntity in project cayenne by apache.

the class CayenneContextIT method testCommitChangesNew.

@Test
public void testCommitChangesNew() {
    final CompoundDiff diff = new CompoundDiff();
    final Object newObjectId = ObjectId.of("test", "key", "generated");
    eventManager = new DefaultEventManager(0);
    // test that ids that are passed back are actually propagated to the
    // right
    // objects...
    MockDataChannel channel = new MockDataChannel() {

        @Override
        public GraphDiff onSync(ObjectContext originatingContext, GraphDiff changes, int syncType) {
            return diff;
        }

        // must provide a channel with working event manager
        @Override
        public EventManager getEventManager() {
            return eventManager;
        }
    };
    CayenneContext context = new CayenneContext(channel);
    ObjEntity entity = new ObjEntity("test_entity");
    entity.setClassName(MockPersistentObject.class.getName());
    DataMap dataMap = new DataMap("test");
    dataMap.addObjEntity(entity);
    Collection<DataMap> entities = Collections.singleton(dataMap);
    context.setEntityResolver(new EntityResolver(entities));
    Persistent object = context.newObject(MockPersistentObject.class);
    // record change here to make it available to the anonymous connector
    // method..
    diff.add(new NodeIdChangeOperation(object.getObjectId(), newObjectId));
    // check that a generated object ID is assigned back to the object...
    assertNotSame(newObjectId, object.getObjectId());
    context.commitChanges();
    assertSame(newObjectId, object.getObjectId());
    assertSame(object, context.graphManager.getNode(newObjectId));
}
Also used : NodeIdChangeOperation(org.apache.cayenne.graph.NodeIdChangeOperation) GraphDiff(org.apache.cayenne.graph.GraphDiff) DefaultEventManager(org.apache.cayenne.event.DefaultEventManager) EntityResolver(org.apache.cayenne.map.EntityResolver) DataMap(org.apache.cayenne.map.DataMap) ObjEntity(org.apache.cayenne.map.ObjEntity) CompoundDiff(org.apache.cayenne.graph.CompoundDiff) Test(org.junit.Test)

Aggregations

ObjEntity (org.apache.cayenne.map.ObjEntity)294 Test (org.junit.Test)110 DbEntity (org.apache.cayenne.map.DbEntity)72 ObjAttribute (org.apache.cayenne.map.ObjAttribute)68 ObjRelationship (org.apache.cayenne.map.ObjRelationship)62 DataMap (org.apache.cayenne.map.DataMap)57 DbAttribute (org.apache.cayenne.map.DbAttribute)37 DbRelationship (org.apache.cayenne.map.DbRelationship)29 CayenneRuntimeException (org.apache.cayenne.CayenneRuntimeException)27 ObjectId (org.apache.cayenne.ObjectId)26 ClassDescriptor (org.apache.cayenne.reflect.ClassDescriptor)22 ArrayList (java.util.ArrayList)19 Embeddable (org.apache.cayenne.map.Embeddable)18 EntityResolver (org.apache.cayenne.map.EntityResolver)17 DataChannelDescriptor (org.apache.cayenne.configuration.DataChannelDescriptor)16 Expression (org.apache.cayenne.exp.Expression)15 Persistent (org.apache.cayenne.Persistent)12 EntityEvent (org.apache.cayenne.map.event.EntityEvent)12 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)12 Entity (org.apache.cayenne.map.Entity)11