Use Transactions in GridGain 9
Group multiple SQL operations into atomic units that either commit together or roll back. Master explicit, managed, and async transaction patterns in Java.
Introduction
Every operation in Work with RecordView and KeyValueView passed null as the transaction parameter. That null tells GridGain to wrap each operation in its own auto-commit transaction: each write commits independently, and there is no coordination between them. When you need multiple operations to succeed or fail together (creating an invoice with its line items, transferring funds between accounts, updating inventory and confirming an order), you replace null with a named Transaction object.
This tutorial builds a music store invoice workflow that writes to two tables inside one atomic unit. You see the full explicit lifecycle (begin, multi-table writes, commit), verify atomicity by rolling back a partial invoice, then refactor to the runInTransaction pattern that handles commit, rollback, and retry automatically. A final step shows the same workflow non-blocking with runInTransactionAsync.
Prerequisites
A running 3-node cluster with the Music Store dataset from Start Your Local GridGain 9 Development Cluster
Completed Work with RecordView and KeyValueView (familiarity with
IgniteClient,IgniteSql, and the Music Store schema)Java 17 or later
Maven 3.8 or later
What You Will Learn
How to group multiple table operations into a single atomic transaction
How to verify atomicity by rolling back a partially created invoice
How
runInTransactionsimplifies lifecycle management with auto-commit, auto-rollback, and auto-retryHow to run transactions asynchronously with
runInTransactionAsyncandCompletableFuture
What You Will Build
You extend the project from Work with RecordView and KeyValueView with four new Java classes, each using a different transaction pattern to create an invoice with line items in the Music Store database. The workflow writes to two tables (Invoice and InvoiceLine) in a single atomic operation. The classes build in sophistication from the explicit lifecycle to the functional runInTransaction pattern to async execution:
All classes clean up their test data, so you can run them in any order.
Verify the Invoice Tables
Before writing transactional code, verify the Invoice and InvoiceLine tables are loaded with the expected data. The Music Store dataset includes 412 invoices and 2,240 invoice line items. Your test classes use IDs starting at 10001, well above the existing dataset range.
Create an Invoice With an Explicit Transaction
An explicit transaction gives you direct control over the lifecycle. You begin it, execute operations, and commit or roll back based on the result.
In Work with RecordView and KeyValueView, every SQL call passed null as the first argument. That null creates an implicit transaction that commits immediately. In this step, you replace null with a named Transaction object. The cluster holds all writes in an uncommitted state until you call tx.commit(). If anything fails before the commit, a tx.rollback() discards every write in the transaction as if none of them happened.
The workflow looks up the unit price for three tracks, inserts one line item per track (accumulating the total), then inserts the invoice header with the calculated total. All four writes are grouped into one atomic unit. No partial state is ever visible to other transactions.
Create CreateInvoice.java in src/main/java/com/example/musicstore/:
Run the class:
What the output shows:
The "Verifying within transaction" block demonstrates read-your-own-writes, a property of GridGain's SERIALIZABLE isolation. Your transaction can read its own uncommitted writes. The data is visible within tx even though no commit has happened. Other transactions running on the cluster at the same time cannot see invoice 10001 or its line items until the commit completes.
The two verification queries are structurally identical but behave differently. The first executes within tx (uncommitted context) and the second executes with (Transaction) null (implicit auto-commit, reads only committed data).
Roll Back a Partial Invoice
The value of transactions is clearest when something goes wrong mid-workflow. This step creates an invoice header, then deliberately fails before inserting line items. In both cases, the invoice header vanishes on rollback. No partial record persists.
The class demonstrates two rollback patterns:
Part A, Explicit rollback: the application decides to cancel and calls
tx.rollback()directly (no exception was thrown)Part B, Error-triggered rollback: an exception interrupts the workflow and the catch block calls
tx.rollback()before re-surfacing the error
Create RollbackInvoice.java:
Run the class:
Why both invoices are gone: The INSERT wrote the invoice header to an uncommitted transaction buffer. tx.rollback() discards that buffer entirely. The write never reached durable storage. From the perspective of any other transaction on the cluster, invoice 10002 and invoice 10003 never existed. Without transactions, the INSERT would have committed immediately and left behind an orphaned invoice record with no line items.
Refactor to runInTransaction
The invoice workflow works, but the begin() / try / commit() / catch / rollback() lifecycle code is boilerplate that every transactional workflow repeats. runInTransaction collapses all of it into a closure:
Auto-commit: GridGain commits the transaction when the closure returns normally
Auto-rollback: GridGain rolls back if the closure throws any exception
Auto-retry: GridGain retries the closure on transient failures (lock conflicts, timeouts, or primary replica changes) without any retry logic in your code
The closure signature is Function<Transaction, T> rather than Consumer<Transaction> because real workflows need to return a value. In this case the workflow returns the new invoice ID, which the caller uses after the transaction commits.
Create InvoiceWorkflow.java:
Run the class:
The runInTransaction version eliminates begin(), the try / catch(Exception e) block, tx.commit(), and tx.rollback(). The workflow code (price lookups, line item inserts, header insert) is unchanged. GridGain manages the lifecycle; your code focuses on the business logic.
Async Transactions
runInTransactionAsync is the non-blocking form of the same pattern. The method returns immediately with a CompletableFuture<T> that completes when the transaction commits. The closure signature is Function<Transaction, CompletableFuture<T>>: the closure must return a future representing the async work, and the transaction commits when that future completes.
When async transactions matter: Services that handle many concurrent requests cannot afford one thread per transaction. A blocking call to runInTransaction occupies the calling thread for the entire round-trip to the cluster. runInTransactionAsync frees the calling thread immediately so it can handle other work while waiting for the commit.
The workflow logic inside the closure is unchanged. The differences are structural. The operations are wrapped in CompletableFuture.supplyAsync() to lift synchronous SQL calls into a future, and post-commit work chains on with thenAccept. In a fully async service, you would replace supplyAsync with chained async GridGain operations using thenCompose.
Create AsyncInvoiceWorkflow.java:
Run the class:
The output is identical to the synchronous InvoiceWorkflow. From the cluster's perspective the transaction is the same: begin, write, commit. The difference is in the calling thread: runInTransactionAsync returned immediately after the closure was submitted. The thenAccept handler ran on a separate thread when the future resolved.
.join() at the end of the chain blocks main() until the async work completes. A standalone main() has no event loop; without .join() the JVM would exit before the future resolves. In a servlet container or reactive framework, you return the future to the framework instead.
Summary
You have written the same multi-table invoice workflow at three levels of sophistication:
Explicit lifecycle. begin() / commit() / rollback(). You control every step. The explicit pattern is the right choice when you need fine-grained control, when you are debugging a transaction, or when the workflow has branch points where you decide to commit or roll back based on business logic before any exception is thrown.
runInTransaction. A closure-based pattern that auto-commits on success, auto-rolls-back on failure, and auto-retries on transient errors. This is the recommended pattern for production code. The boilerplate is gone; the workflow logic is unchanged.
runInTransactionAsync. The same pattern, non-blocking. Use this in services that handle many concurrent requests and cannot afford one thread per in-flight transaction.
When to choose each pattern:
Explicit begin() / commit()
Debugging, branch-based commit decisions, fine-grained lifecycle control
runInTransaction
Standard production workflows, most multi-table operations
runInTransactionAsync
High-concurrency services, event-driven architectures, reactive pipelines
Continue to Design a Schema for Distributed SQL to learn how colocation and distribution zones shape performance. To run Java logic directly on the nodes where data lives, see About Distributed Computing.
This page is: Copyright © 2026 MariaDB. All rights reserved.
Last updated
Was this helpful?

