在Neo4j Java中的事务关闭/提交问题

huangapple go评论69阅读模式
英文:

Transaction close/commit issue in Neo4j Java

问题

我是新来的Neo4j用户。我正在使用Neo4j数据库编写一个Java程序,遇到了在创建节点时遇到的问题。

我在创建新节点时使用了一个事务,然后我想打印它的ID,使用 node.getProperty(ID)。但是我收到了如下所示的错误消息。所以我的问题是,在Java中使用事务时,我们应该在什么时候创建、提交/关闭事务?在创建或搜索节点时,我们是否需要每次都创建一个新事务并进行提交/关闭呢?

Exception in thread "main" org.neo4j.graphdb.NotInTransactionException: 事务已关闭。
	at org.neo4j.kernel.impl.coreapi.TransactionImpl.checkInTransaction(TransactionImpl.java:695)
	at org.neo4j.kernel.impl.coreapi.TransactionImpl.kernelTransaction(TransactionImpl.java:576)
	at org.neo4j.kernel.impl.core.NodeEntity.getProperty(NodeEntity.java:428)

更新:我最初的事务代码是这样的

Node n;
try(Transaction tx = graphDB.beginTx()){
   n = tx.createNode(label);
   n.setProperty(PROPERTY,value);
   tx.commit();
}
System.out.println(n.getProperty(PROPERTY));

现在我将打印语句移到了try子句中,以便它在同一个事务中。

英文:

I'm new to Neo4j. I'm writing a java program using Neo4j database, and I met an issue when I create a node.

I use one transaction for creating the new node, and then I want to print its id, using node.getProperty(ID). But I got error message as attached below. So my question is, when using transaction in java, when should we create and commit/close it? Do we need to create a new transaction and commit/close it each time when creating or searching a node?

Exception in thread "main" org.neo4j.graphdb.NotInTransactionException: The transaction has been closed.
	at org.neo4j.kernel.impl.coreapi.TransactionImpl.checkInTransaction(TransactionImpl.java:695)
	at org.neo4j.kernel.impl.coreapi.TransactionImpl.kernelTransaction(TransactionImpl.java:576)
	at org.neo4j.kernel.impl.core.NodeEntity.getProperty(NodeEntity.java:428)

Update: My original transaction code is like this

Node n;
try(Transaction tx = graphDB.beginTx(){
   n = tx.createNode(label);
   n.setProperty(PROPERTY,value);
   tx.commit();
}
System.out.println(n.getProperty(PROPERTY));

Now I moved the print line to the try clause so it's in the same transaction.

答案1

得分: 1

由交易提供的Node对象仅在交易生命周期内有效。如果您希望在交易之外使用节点属性的值,应在交易期间获取该值并将其存储在适当的位置。

英文:

A Node object provided by a transaction is only valid for the life of the transaction. If you want to use the value of a node property outside of the transaction, you should get the value and store it someplace suitable during the transaction.

huangapple
  • 本文由 发表于 2020年9月3日 08:48:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63715290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定