• Start

Languages

/

Java

/

API Reference

/

Core

Transaction

The Transaction class provides methods for executing queries within an atomic transaction.

The Transaction class wraps a set of operations into an atomic unit. Changes made within a transaction are only applied when committed, and can be rolled back by cancelling. Transactions are created by calling .beginTransaction() on a Surreal instance.

Source: surrealdb.java

Note

The Transaction class only supports .query() with raw SurrealQL strings. Parameterised queries via .queryBind() are not available inside transactions. To pass dynamic values, interpolate them directly in the SurrealQL string or use SurrealQL parameters defined earlier in the transaction.

Executes a SurrealQL query within the transaction. The query results are not visible outside the transaction until it is committed.

Method Syntax
tx.query(sql)

Parameter

Type

Description

sqlString

The SurrealQL query string to execute within the transaction.

Returns: Response

Example
Transaction tx = db.beginTransaction();
Response response = tx.query("CREATE person SET name = 'Alice'");
tx.commit();

Commits the transaction, applying all changes made within it to the database. After committing, the transaction object should not be reused.

Method Syntax
tx.commit()

Returns: void

Example
Transaction tx = db.beginTransaction();
tx.query("CREATE person SET name = 'Alice'");
tx.query("CREATE person SET name = 'Bob'");
tx.commit();

Cancels the transaction, discarding all changes made within it. No data is written to the database. After cancelling, the transaction object should not be reused.

Method Syntax
tx.cancel()

Returns: void

Example
Transaction tx = db.beginTransaction();
tx.query("DELETE person");
tx.cancel();
Atomic transfer
import com.surrealdb.Surreal;
import com.surrealdb.Transaction;
import com.surrealdb.signin.RootCredential;

try (Surreal db = new Surreal()) {
    db.connect("ws://localhost:8000");
    db.useNs("bank").useDb("ledger");
    db.signin(new RootCredential("root", "root"));

    Transaction tx = db.beginTransaction();
    try {
        tx.query("UPDATE accounts:alice SET balance = balance - 200");
        tx.query("UPDATE accounts:bob SET balance = balance + 200");
        tx.commit();
    } catch (Exception e) {
        tx.cancel();
        throw e;
    }
}

Was this page helpful?