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

Methods

.query(sql)

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)
ParameterTypeDescription
sql StringThe 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();

.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();

.cancel()

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

Complete Example

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

See Also