Search in sources :

Example 16 with Persistent

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

the class ObjectStore method postprocessAfterCommit.

/**
 * Internal unsynchronized method to process objects state after commit.
 *
 * @since 1.2
 */
void postprocessAfterCommit(GraphDiff parentChanges) {
    // scan through changed objects, set persistence state to committed
    for (Object id : changes.keySet()) {
        Persistent object = objectMap.get(id);
        switch(object.getPersistenceState()) {
            case PersistenceState.DELETED:
                objectMap.remove(id);
                object.setObjectContext(null);
                object.setPersistenceState(PersistenceState.TRANSIENT);
                break;
            case PersistenceState.NEW:
            case PersistenceState.MODIFIED:
                object.setPersistenceState(PersistenceState.COMMITTED);
                break;
        }
    }
    // re-register changed object ids
    if (!parentChanges.isNoop()) {
        parentChanges.apply(new GraphChangeHandler() {

            @Override
            public void arcCreated(Object nodeId, Object targetNodeId, Object arcId) {
            }

            @Override
            public void arcDeleted(Object nodeId, Object targetNodeId, Object arcId) {
            }

            @Override
            public void nodeCreated(Object nodeId) {
            }

            @Override
            public void nodeIdChanged(Object nodeId, Object newId) {
                processIdChange(nodeId, newId);
            }

            @Override
            public void nodePropertyChanged(Object nodeId, String property, Object oldValue, Object newValue) {
            }

            @Override
            public void nodeRemoved(Object nodeId) {
            }
        });
    }
    // create new instance of changes map so that event listeners who stored the
    // original diff don't get affected
    this.changes = new HashMap<>();
}
Also used : DataObject(org.apache.cayenne.DataObject) Persistent(org.apache.cayenne.Persistent) GraphChangeHandler(org.apache.cayenne.graph.GraphChangeHandler)

Example 17 with Persistent

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

the class ObjectStoreGraphDiff method preprocess.

private void preprocess(ObjectStore objectStore) {
    Map<Object, ObjectDiff> changes = getChangesByObjectId();
    if (!changes.isEmpty()) {
        for (Entry<Object, ObjectDiff> entry : changes.entrySet()) {
            ObjectId id = (ObjectId) entry.getKey();
            Persistent object = (Persistent) objectStore.getNode(id);
            // address manual id override.
            ObjectId objectId = object.getObjectId();
            if (!id.equals(objectId)) {
                if (objectId != null) {
                    Map<String, Object> replacement = id.getReplacementIdMap();
                    replacement.clear();
                    replacement.putAll(objectId.getIdSnapshot());
                }
                object.setObjectId(id);
            }
        }
    }
}
Also used : ObjectId(org.apache.cayenne.ObjectId) Persistent(org.apache.cayenne.Persistent)

Example 18 with Persistent

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

the class ResultScanParentAttachmentStrategy method indexParents.

private void indexParents() {
    partitionByChild = new HashMap<>();
    List<Persistent> objects = parentNode.getObjects();
    // this can be null if parent node returned no rows
    if (objects == null) {
        return;
    }
    List<DataRow> rows = parentNode.getDataRows();
    if (rows == null) {
        return;
    }
    int size = objects.size();
    for (int i = 0; i < size; i++) {
        DataRow row = rows.get(i);
        Object key;
        if (joins.length > 1) {
            List<Object> values = new ArrayList<>(joins.length);
            for (int j = 0; j < joins.length; j++) {
                values.add(row.get(joins[j].getSourceName()));
            }
            key = values;
        } else {
            key = row.get(joins[0].getSourceName());
        }
        List<Persistent> parents = partitionByChild.get(key);
        if (parents == null) {
            parents = new ArrayList<>();
            partitionByChild.put(key, parents);
        }
        parents.add(objects.get(i));
    }
}
Also used : ArrayList(java.util.ArrayList) Persistent(org.apache.cayenne.Persistent) DataRow(org.apache.cayenne.DataRow)

Example 19 with Persistent

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

the class EJBQLPathAnaliserTranslator method processParameter.

private void processParameter(String boundName, EJBQLExpression expression) {
    Object object = context.getBoundParameter(boundName);
    Map<?, ?> map = null;
    if (object instanceof Persistent) {
        map = ((Persistent) object).getObjectId().getIdSnapshot();
    } else if (object instanceof ObjectId) {
        map = ((ObjectId) object).getIdSnapshot();
    } else if (object instanceof Map) {
        map = (Map<?, ?>) object;
    }
    if (map != null) {
        if (map.size() == 1) {
            context.rebindParameter(boundName, map.values().iterator().next());
        } else {
            addMultiColumnOperand(EJBQLMultiColumnOperand.getObjectOperand(context, map));
            return;
        }
    }
    if (object != null) {
        context.append(" #bind($").append(boundName).append(")");
    } else {
        String type = null;
        Node parent = ((SimpleNode) expression).jjtGetParent();
        context.pushMarker("@processParameter", true);
        EJBQLPathAnaliserTranslator translator = new EJBQLPathAnaliserTranslator(context);
        parent.visit(translator);
        translator.visitPath(parent, parent.getChildrenCount());
        String id = translator.idPath;
        if (id != null) {
            ClassDescriptor descriptor = context.getEntityDescriptor(id);
            if (descriptor == null) {
                throw new EJBQLException("Unmapped id variable: " + id);
            }
            String pathChunk = translator.lastPathComponent;
            PropertyDescriptor property = descriptor.getProperty(pathChunk);
            if (property instanceof AttributeProperty) {
                String atrType = ((AttributeProperty) property).getAttribute().getType();
                type = TypesMapping.getSqlNameByType(TypesMapping.getSqlTypeByJava(atrType));
            }
        }
        context.popMarker();
        if (type == null) {
            type = "VARCHAR";
        }
        // this is a hack to prevent execptions on DB's like Derby for
        // expressions
        // "X = NULL". The 'VARCHAR' parameter is totally bogus, but seems
        // to work on
        // all tested DB's... Also note what JPA spec, chapter 4.11 says:
        // "Comparison
        // or arithmetic operations with a NULL value always yield an
        // unknown value."
        // TODO: andrus 6/28/2007 Ideally we should track the type of the
        // current
        // expression to provide a meaningful type.
        context.append(" #bind($").append(boundName).append(" '" + type + "')");
    }
}
Also used : ClassDescriptor(org.apache.cayenne.reflect.ClassDescriptor) PropertyDescriptor(org.apache.cayenne.reflect.PropertyDescriptor) ObjectId(org.apache.cayenne.ObjectId) SimpleNode(org.apache.cayenne.ejbql.parser.SimpleNode) Node(org.apache.cayenne.ejbql.parser.Node) AggregateConditionNode(org.apache.cayenne.ejbql.parser.AggregateConditionNode) EJBQLException(org.apache.cayenne.ejbql.EJBQLException) Persistent(org.apache.cayenne.Persistent) AttributeProperty(org.apache.cayenne.reflect.AttributeProperty) SimpleNode(org.apache.cayenne.ejbql.parser.SimpleNode) Map(java.util.Map)

Example 20 with Persistent

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

the class ClientChannelTest method testOnQuerySelect.

@Test
public void testOnQuerySelect() {
    final MockPersistentObject o1 = new MockPersistentObject();
    ObjectId oid1 = new ObjectId("test_entity");
    o1.setObjectId(oid1);
    ClientConnection connection = mock(ClientConnection.class);
    when(connection.sendMessage((ClientMessage) any())).thenAnswer(new Answer<Object>() {

        public Object answer(InvocationOnMock invocation) {
            ClientMessage arg = (ClientMessage) invocation.getArguments()[0];
            if (arg instanceof BootstrapMessage) {
                return new EntityResolver();
            } else {
                return new GenericResponse(Arrays.asList(o1));
            }
        }
    });
    ClientChannel channel = new ClientChannel(connection, false, new MockEventManager(), false);
    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));
    QueryResponse response = channel.onQuery(context, new SelectQuery("test_entity"));
    assertNotNull(response);
    List<?> list = response.firstList();
    assertNotNull(list);
    assertEquals(1, list.size());
    Persistent o1_1 = (Persistent) list.get(0);
    assertEquals(o1.getObjectId(), o1_1.getObjectId());
    // ObjectContext must be injected
    assertEquals(context, o1_1.getObjectContext());
    assertSame(o1_1, context.getGraphManager().getNode(oid1));
}
Also used : ObjectId(org.apache.cayenne.ObjectId) GenericResponse(org.apache.cayenne.util.GenericResponse) Persistent(org.apache.cayenne.Persistent) EntityResolver(org.apache.cayenne.map.EntityResolver) CayenneContext(org.apache.cayenne.CayenneContext) DataMap(org.apache.cayenne.map.DataMap) SelectQuery(org.apache.cayenne.query.SelectQuery) ObjEntity(org.apache.cayenne.map.ObjEntity) InvocationOnMock(org.mockito.invocation.InvocationOnMock) MockPersistentObject(org.apache.cayenne.MockPersistentObject) QueryResponse(org.apache.cayenne.QueryResponse) MockPersistentObject(org.apache.cayenne.MockPersistentObject) MockEventManager(org.apache.cayenne.event.MockEventManager) Test(org.junit.Test)

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