使用 Spring 数据更新节点对象

Update a Node object with Spring data

我想更新数据库中的现有节点。 我可以正确创建一个节点,但无法更新现有节点。

try (Transaction tx = template.getGraphDatabaseService().beginTx()) {
    Node node = repository.findNodeUsingId("n1");
    if(node != null){
          //Modify some properties using setProperty 
          node.setProperty("name","P");

          //How should I do to save the modified node object?
    }else{
          //Create the node
          //This part works fine
          node = template.createNode();                       
          node.setProperty("name", "T");
    }
    tx.success();
}

您不必保存修改后的对象。

调用 setProperty 后,您的节点 属性 已在当前交易中设置。

您在这里唯一缺少的是关闭交易,检查这个(来自 Neo4j Javadoc)关于 Transaction.close()

Commits or marks this transaction for rollback, depending on whether success() or failure() has been previously invoked. All ResourceIterables that where returned from operations executed inside this transaction will be automatically closed by this method. This method comes from AutoCloseable so that a Transaction can participate in try-with-resource statements. It will not throw any declared exception. Invoking this method (which is unnecessary when in try-with-resource statement) or finish() has the exact same effect.