我正在构建一个独立的java应用程序,并在嵌入式模式下使用neo4j与Cypher存储信息。我已经构建了这个函数,用于一般目的:
private ExecutionResult runCypher(String query)
{
Transaction tx = service.beginTx();
ExecutionResult result = null;
boolean success = true;
try
{
result = engine.execute(query);
}
catch(Exception e)
{
System.out.println(e.getMessage());
success = false;
}
finally
{
if(success) tx.success();
else tx.failure();
}
tx.close();
return result;
}
问题是我经常遇到这个错误:
Exception in thread "main" org.neo4j.graphdb.TransactionFailureException: Failed to mark transaction as rollback only.
at org.neo4j.kernel.TopLevelTransaction.markAsRollbackOnly(TopLevelTransaction.java:97)
at org.neo4j.kernel.TopLevelTransaction.failure(TopLevelTransaction.java:86)
如果我修改finally子句,并且总是去tx.failure(),那么没有问题。发生了什么事?
答案 0 :(得分:5)
我会将代码更改为:
private ExecutionResult runCypher(String query, Map params) {
try (Transaction tx = service.beginTx()) {
ExecutionResult result = engine.execute(query, params);
// extract the data out of the result, you cannot iterate over it outside of a tx
Collection resultData = ....
tx.success();
return resultData;
}
}
tx.success()
tx.failure()
,系统会自动假设tx.success()