javaneo4jtransactionsneo4j-driver

Does neo4j java driver rollback transactions automatically when an error occurs?


I am running the below code to check if rollback call occurs. However, I am getting this error:

Could not rollback transaction  org.neo4j.driver.exceptions.ClientException: Can't rollback, transaction has been rolled back
    at org.neo4j.driver.internal.util.Futures.blockingGet(Futures.java:143)
    at org.neo4j.driver.internal.InternalTransaction.rollback(InternalTransaction.java:46)

Is it not possible to manually rollback the transaction?

Driver driver = GraphDatabase.driver(neo4jUrl, AuthTokens.basic(neo4jUsername,neo4jPassword));
Session session = driver.session();

Transaction tx = null;
try{
    tx = session.beginTransaction();

    String insertQuery = "CREATE(n:Person{id:8,name:'Person6',age:26}) ";
    tx.run(insertQuery);

    String delQuery = "MATCH(n:Person{id:3}) DELETE n";
   // String delQuery = "MATCH(n:Person{id:2}) DELETE n";
    tx.run(delQuery);

    tx.commit();
    System.out.println("Trnx committed");
}catch(Exception e){
    tx.rollback();
    System.out.println("Transaction rolled back.");
} finally {
    if (session != null) session.close();
    if (driver != null) driver.close();
}

Solution

  • You can check with tx.isOpen(). A simpler solution however is to just close the transaction, if it's not committed, it's going to be rolled back.

    try (Transaction tx = session.beginTransaction()) {
        // try-with-resources automatically closes the transaction
        // [...]
    }
    

    Side note: you don't want to create a driver every time you run a transaction.