• Start

Languages

/

Java

/

Concepts

Transactions

The Java SDK supports client-side transactions for grouping multiple queries into an atomic unit.

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.

Method

Description

db.beginTransaction()

Starts a new transaction

tx.query(sql)

Executes a query within the transaction

tx.commit()

Commits the transaction

tx.cancel()

Cancels (rolls back) the 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();

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.

Note

Parameterised 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");

Call .commit() to apply all changes atomically. Once committed, the changes become visible to other connections and queries.

tx.commit();

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;
}

Was this page helpful?