Search in sources :

Example 21 with Statement

use of org.neo4j.ogm.request.Statement in project neo4j-ogm by neo4j.

the class DeleteDelegate method deleteAll.

/**
 * Deletes all nodes of a given type. They will get discovered by using the matching label for that type.
 * To avoid a delete of every node in the database the method will abort the delete operation if no label
 * can be determined.
 *
 * @param type  The type of the nodes/objects to be deleted.
 * @param <T>   The type to work with
 */
public <T> void deleteAll(Class<T> type) {
    ClassInfo classInfo = session.metaData().classInfo(type.getName());
    if (classInfo != null) {
        String entityLabel = classInfo.neo4jName();
        if (entityLabel == null) {
            session.warn("Unable to find database label for entity " + type.getName() + " : no results will be returned. Make sure the class is registered, " + "and not abstract without @NodeEntity annotation");
            return;
        }
        Statement request = getDeleteStatementsBasedOnType(type).delete(entityLabel);
        RowModelRequest query = new DefaultRowModelRequest(request.getStatement(), request.getParameters());
        session.notifyListeners(new PersistenceEvent(type, Event.TYPE.PRE_DELETE));
        session.doInTransaction(() -> {
            try (Response<RowModel> response = session.requestHandler().execute(query)) {
                session.context().removeType(type);
                if (session.eventsEnabled()) {
                    session.notifyListeners(new PersistenceEvent(type, Event.TYPE.POST_DELETE));
                }
            }
        }, Transaction.Type.READ_WRITE);
    } else {
        session.warn(type.getName() + " is not a persistable class");
    }
}
Also used : Statement(org.neo4j.ogm.request.Statement) PersistenceEvent(org.neo4j.ogm.session.event.PersistenceEvent) RowModelRequest(org.neo4j.ogm.request.RowModelRequest) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest) RowModel(org.neo4j.ogm.model.RowModel) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest)

Example 22 with Statement

use of org.neo4j.ogm.request.Statement in project neo4j-ogm by neo4j.

the class DeleteDelegate method deleteOneOrMoreObjects.

// TODO : this is being done in multiple requests at the moment, one per object. Why not put them in a single request?
private void deleteOneOrMoreObjects(List<?> objects, Set<Object> neighbours) {
    Set<Object> notified = new HashSet<>();
    if (session.eventsEnabled()) {
        for (Object affectedObject : neighbours) {
            if (!notified.contains(affectedObject)) {
                session.notifyListeners(new PersistenceEvent(affectedObject, Event.TYPE.PRE_SAVE));
                notified.add(affectedObject);
            }
        }
    }
    for (Object object : objects) {
        MetaData metaData = session.metaData();
        ClassInfo classInfo = metaData.classInfo(object);
        if (classInfo == null) {
            session.warn(object.getClass().getName() + " is not an instance of a persistable class");
        } else {
            MappingContext mappingContext = session.context();
            Long id = mappingContext.optionalNativeId(object).filter(possibleId -> possibleId >= 0).orElseGet(() -> {
                session.warn(String.format("Instance of class %s has to be reloaded to be deleted. This can happen if the session has " + "been cleared between loading and deleting or using an object from a different transaction.", object.getClass()));
                return classInfo.getPrimaryIndexOrIdReader().apply(object).map(primaryIndexOrId -> session.load(object.getClass(), (Serializable) primaryIndexOrId)).flatMap(reloadedObject -> mappingContext.optionalNativeId(reloadedObject)).orElse(-1L);
            });
            if (id >= 0) {
                Statement request = getDeleteStatement(object, id, classInfo);
                if (session.eventsEnabled() && !notified.contains(object)) {
                    session.notifyListeners(new PersistenceEvent(object, Event.TYPE.PRE_DELETE));
                    notified.add(object);
                }
                RowModelRequest query = new DefaultRowModelRequest(request.getStatement(), request.getParameters());
                session.doInTransaction(() -> {
                    try (Response<RowModel> response = session.requestHandler().execute(query)) {
                        if (request.optimisticLockingConfig().isPresent()) {
                            List<RowModel> rowModels = response.toList();
                            session.optimisticLockingChecker().checkResultsCount(rowModels, request);
                        }
                        if (metaData.isRelationshipEntity(classInfo.name())) {
                            session.detachRelationshipEntity(id);
                        } else {
                            session.detachNodeEntity(id);
                        }
                        // enabled in the first place.
                        if (notified.contains(object)) {
                            session.notifyListeners(new PersistenceEvent(object, Event.TYPE.POST_DELETE));
                        }
                    }
                }, Transaction.Type.READ_WRITE);
            }
        }
    }
    if (session.eventsEnabled()) {
        for (Object affectedObject : neighbours) {
            if (notified.contains(affectedObject)) {
                session.notifyListeners(new PersistenceEvent(affectedObject, Event.TYPE.POST_SAVE));
            }
        }
    }
}
Also used : Arrays(java.util.Arrays) CypherQuery(org.neo4j.ogm.cypher.query.CypherQuery) Response(org.neo4j.ogm.response.Response) Neo4jSession(org.neo4j.ogm.session.Neo4jSession) MappingContext(org.neo4j.ogm.context.MappingContext) RowModelRequest(org.neo4j.ogm.request.RowModelRequest) RelationshipDeleteStatements(org.neo4j.ogm.session.request.strategy.impl.RelationshipDeleteStatements) ArrayList(java.util.ArrayList) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest) HashSet(java.util.HashSet) RowModel(org.neo4j.ogm.model.RowModel) Map(java.util.Map) Event(org.neo4j.ogm.session.event.Event) Transaction(org.neo4j.ogm.transaction.Transaction) PersistenceEvent(org.neo4j.ogm.session.event.PersistenceEvent) Result(org.neo4j.ogm.model.Result) DeleteStatements(org.neo4j.ogm.session.request.strategy.DeleteStatements) MetaData(org.neo4j.ogm.metadata.MetaData) Set(java.util.Set) NodeDeleteStatements(org.neo4j.ogm.session.request.strategy.impl.NodeDeleteStatements) Filter(org.neo4j.ogm.cypher.Filter) Statement(org.neo4j.ogm.request.Statement) Serializable(java.io.Serializable) List(java.util.List) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) Collections(java.util.Collections) Serializable(java.io.Serializable) Statement(org.neo4j.ogm.request.Statement) RowModelRequest(org.neo4j.ogm.request.RowModelRequest) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest) MappingContext(org.neo4j.ogm.context.MappingContext) PersistenceEvent(org.neo4j.ogm.session.event.PersistenceEvent) MetaData(org.neo4j.ogm.metadata.MetaData) RowModel(org.neo4j.ogm.model.RowModel) HashSet(java.util.HashSet) ClassInfo(org.neo4j.ogm.metadata.ClassInfo) DefaultRowModelRequest(org.neo4j.ogm.cypher.query.DefaultRowModelRequest)

Example 23 with Statement

use of org.neo4j.ogm.request.Statement in project neo4j-ogm by neo4j.

the class MultiStatementCypherCompiler method createRelationshipsStatements.

@Override
public List<Statement> createRelationshipsStatements() {
    assertStatementFactoryExists();
    // Group relationships by type and non-null properties
    // key: relationship type, value: Map where key=Set<Property strings>, value: Set of edges with those properties
    Map<String, Map<String, Set<Edge>>> relsByTypeAndProps = new HashMap<>();
    for (RelationshipBuilder relationshipBuilder : newRelationshipBuilders) {
        if (relationshipBuilder.edge().getStartNode() == null || relationshipBuilder.edge().getEndNode() == null) {
            // TODO this is a carry forward from the old emitters. We want to prevent this rel builder getting created or remove it
            continue;
        }
        Map<String, Set<Edge>> relsByProps = relsByTypeAndProps.computeIfAbsent(relationshipBuilder.type(), (key) -> new HashMap<>());
        RelationshipModel edge = (RelationshipModel) relationshipBuilder.edge();
        String primaryId = edge.getPrimaryIdName();
        Set<Edge> rels = relsByProps.computeIfAbsent(primaryId, (s) -> new HashSet<>());
        edge.setStartNode(context.getId(edge.getStartNode()));
        edge.setEndNode(context.getId(edge.getEndNode()));
        rels.add(edge);
    }
    List<Statement> statements = new ArrayList<>();
    // For each relationship type
    for (Map<String, Set<Edge>> edgesByProperties : relsByTypeAndProps.values()) {
        // For each set of unique property keys
        for (Set<Edge> edges : edgesByProperties.values()) {
            NewRelationshipStatementBuilder newRelationshipBuilder = new NewRelationshipStatementBuilder(edges, statementFactory);
            statements.add(newRelationshipBuilder.build());
        }
    }
    return statements;
}
Also used : Statement(org.neo4j.ogm.request.Statement) RelationshipModel(org.neo4j.ogm.response.model.RelationshipModel) NewRelationshipStatementBuilder(org.neo4j.ogm.cypher.compiler.builders.statement.NewRelationshipStatementBuilder) Edge(org.neo4j.ogm.model.Edge) DefaultRelationshipBuilder(org.neo4j.ogm.cypher.compiler.builders.node.DefaultRelationshipBuilder)

Example 24 with Statement

use of org.neo4j.ogm.request.Statement in project neo4j-ogm by neo4j.

the class MultiStatementCypherCompiler method deleteRelationshipStatements.

@Override
public List<Statement> deleteRelationshipStatements() {
    assertStatementFactoryExists();
    // Group relationships by type
    Map<String, Set<Edge>> deletedRelsByType = groupRelationshipsByType(deletedRelationshipBuilders);
    List<Statement> statements = new ArrayList<>();
    for (Set<Edge> edges : deletedRelsByType.values()) {
        DeletedRelationshipStatementBuilder deletedRelationshipBuilder = new DeletedRelationshipStatementBuilder(edges, statementFactory);
        statements.add(deletedRelationshipBuilder.build());
    }
    return statements;
}
Also used : Statement(org.neo4j.ogm.request.Statement) Edge(org.neo4j.ogm.model.Edge) DeletedRelationshipStatementBuilder(org.neo4j.ogm.cypher.compiler.builders.statement.DeletedRelationshipStatementBuilder)

Example 25 with Statement

use of org.neo4j.ogm.request.Statement in project neo4j-ogm by neo4j.

the class MultiStatementCypherCompiler method createNodesStatements.

public List<Statement> createNodesStatements() {
    assertStatementFactoryExists();
    Map<String, Set<Node>> newNodesByLabels = groupNodesByLabel(newNodeBuilders);
    List<Statement> statements = new ArrayList<>(newNodesByLabels.size());
    for (Set<Node> nodeModels : newNodesByLabels.values()) {
        NewNodeStatementBuilder newNodeBuilder = new NewNodeStatementBuilder(nodeModels, statementFactory);
        statements.add(newNodeBuilder.build());
    }
    return statements;
}
Also used : Statement(org.neo4j.ogm.request.Statement) Node(org.neo4j.ogm.model.Node) NewNodeStatementBuilder(org.neo4j.ogm.cypher.compiler.builders.statement.NewNodeStatementBuilder)

Aggregations

Statement (org.neo4j.ogm.request.Statement)38 ArrayList (java.util.ArrayList)20 Test (org.junit.Test)19 List (java.util.List)15 MappedRelationship (org.neo4j.ogm.context.MappedRelationship)10 Compiler (org.neo4j.ogm.cypher.compiler.Compiler)7 Map (java.util.Map)6 Document (org.neo4j.ogm.domain.filesystem.Document)6 Folder (org.neo4j.ogm.domain.filesystem.Folder)6 RowModel (org.neo4j.ogm.model.RowModel)6 RowStatementFactory (org.neo4j.ogm.session.request.RowStatementFactory)5 Teacher (org.neo4j.ogm.domain.education.Teacher)4 HashMap (java.util.HashMap)3 Set (java.util.Set)3 DefaultRowModelRequest (org.neo4j.ogm.cypher.query.DefaultRowModelRequest)3 Forum (org.neo4j.ogm.domain.forum.Forum)3 ForumTopicLink (org.neo4j.ogm.domain.forum.ForumTopicLink)3 Topic (org.neo4j.ogm.domain.forum.Topic)3 Node (org.neo4j.ogm.model.Node)3 Arrays (java.util.Arrays)2