我正在试图找出交易(我正在使用neo4j 1.8.2),但无法理解我如何处理错误。
例如我正在创建节点:
public Node createNode() {
Transaction tx = getGraphDb().beginTx();
try {
Node node = graphDb.createNode();
tx.success();
return node;
} finally {
tx.finish();
}
}
如果未创建节点会怎么样?如何获取节点?我应该检查节点是否为空?
答案 0 :(得分:2)
您可以使用以下代码段。 catch子句中的异常将告诉您出了什么问题。
Transaction tx = graphDb.beginTx();
Node n = null;
try {
n = graphDb.createNode();
tx.success();
} catch (Exception e) {
tx.failure();
} finally {
tx.finish();
}
当调用tx.finish()
时,事务将在tx.failure()
上回滚。
注意:org.neo4j.graphdb.Transaction.finish()已弃用,以支持try-with-resource语句,请参阅:http://javadox.com/org.neo4j/neo4j-kernel/2.0.3/deprecated-list.html。
现在正确的方法是:
try ( Transaction tx = graphDatabaseService.beginTx() )
{
//work here
tx.success();
}
答案 1 :(得分:1)
tx.failure()。缺少tx.success()也会回滚事务。所以你可以说它是异常控制的事务管理。