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

36 Views Asked by At

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();
}
2

There are 2 best solutions below

3
fbiville On BEST ANSWER

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.

4
cybersam On

A transaction is automatically rolled back if it fails.

The (very confusing) error message "Can't rollback, transaction has been rolled back" is trying to tell you that your attempt to roll back failed because the transaction was already rolled back.

Also, as suggested by @fbiville, the documented suggestion is to wrap the transaction in:

a try-with-resources block, which ensures in case of any error in try block, the transaction is automatically rolled back on close. Note that ROLLBACK is the default action unless commit() is called before closing.