javaneo4j

How to rollback Neo4j transaction outside a Session


I have a Java application that connects to Neo4j. I want to test the rollback ability for my project, so I have created a sample code. First, I am opening a session, perform a write transaction and commit it. After the session gets closed, I need to rollback my previous transaction (outside the session)

public class Neo4jTransactionExample {
  public void main() {
      createPersonsWithReference();
      rollback();
  }
  public void createPersonsWithReference() {
      try (Session session = driver.session()) {
          session.writeTransaction(tx -> {
              tx.run("CREATE (a:Person {name: 'Alice'})");
              tx.run("CREATE (b:Person {name: 'Bob'})");
              tx.run("MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}) CREATE (b)-[:KNOWS]->(a)");
              return null;
          });
      }
  }

  public void rollback() {
  
  }
}

How do I perform rollback after the session gets closed?


Solution

  • Transactions created in a session are confined to that session, so you cannot rollback a transaction from outside that session.

    Also, even within a session, you cannot rollback a transaction after it is committed (or rolled back). writeTransaction creates and commits/rolls-back a transaction for you.