Transactions
The Java SDK supports client-side transactions for grouping multiple queries into an atomic unit. All queries within a Transaction are isolated from other operations and are either applied together on commit or discarded entirely on cancel.
API References
Starting a transaction
The .beginTransaction() method returns a Transaction object. All queries executed through this object are isolated until the transaction is committed or cancelled.
Transaction tx = db.beginTransaction();
Executing queries in a transaction
The tx.query() method works like db.query() but executes within the transaction scope. Each call returns a Response that you can inspect immediately, but the underlying changes are not visible outside the transaction until it is committed.
Parameterized queries via .queryBind() are not available inside transactions. To pass dynamic values, use SurrealQL LET statements or inline the values in the query string.
Transaction tx = db.beginTransaction();
tx.query("CREATE account:one SET balance = 100");
tx.query("CREATE account:two SET balance = 0");
Committing a transaction
Call .commit() to apply all changes atomically. Once committed, the changes become visible to other connections and queries.
tx.commit();
Cancelling a transaction
Call .cancel() to discard all changes made within the transaction. Use a try-catch pattern to ensure the transaction is rolled back if any query fails.
Transaction tx = db.beginTransaction();
try {
tx.query("CREATE account:one SET balance = 100");
tx.query("CREATE account:two SET balance = 0");
tx.query("UPDATE account:one SET balance -= 50");
tx.query("UPDATE account:two SET balance += 50");
tx.commit();
} catch (SurrealException e) {
tx.cancel();
throw e;
}
Learn more