Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

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

Returning to these tutorials? Restore your project.

This tutorial extends the Maven project from Work with RecordView and KeyValueView. If you need to recreate that project, create a directory named table-api-demo with the following files.

pom.xml

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>table-api-demo</artifactId>
    <version>1.0.0</version>

    <properties>
        <maven.compiler.release>17</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <exec.mainClass>com.example.musicstore.CreateInvoice</exec.mainClass>
    </properties>

    <repositories>
        <repository>
            <id>gridgain-external</id>
            <url>https://www.gridgainsystems.com/nexus/content/repositories/external</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.gridgain</groupId>
            <artifactId>ignite-client</artifactId>
            <!-- Use the latest GridGain 9 version -->
            <version>9.1.28</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>3.4.1</version>
                <configuration>
                    <mainClass>${exec.mainClass}</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Model classes. Create these in src/main/java/com/example/musicstore/model/:

model/Artist.java
package com.example.musicstore.model;

public class Artist {
    private Integer artistId;
    private String name;

    public Artist() {}

    public Artist(Integer artistId, String name) {
        this.artistId = artistId;
        this.name = name;
    }

    public Integer getArtistId() { return artistId; }
    public void setArtistId(Integer artistId) { this.artistId = artistId; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    @Override
    public String toString() {
        return "Artist{id=" + artistId + ", name='" + name + "'}";
    }
}
model/Customer.java
package com.example.musicstore.model;

public class Customer {
    private Integer customerId;
    private String firstName;
    private String lastName;
    private String company;
    private String address;
    private String city;
    private String state;
    private String country;
    private String postalCode;
    private String phone;
    private String fax;
    private String email;
    private Integer supportRepId;

    public Customer() {}

    public Customer(Integer customerId) {
        this.customerId = customerId;
    }

    public Integer getCustomerId() { return customerId; }
    public void setCustomerId(Integer id) { this.customerId = id; }
    public String getFirstName() { return firstName; }
    public void setFirstName(String v) { this.firstName = v; }
    public String getLastName() { return lastName; }
    public void setLastName(String v) { this.lastName = v; }
    public String getCompany() { return company; }
    public void setCompany(String v) { this.company = v; }
    public String getAddress() { return address; }
    public void setAddress(String v) { this.address = v; }
    public String getCity() { return city; }
    public void setCity(String v) { this.city = v; }
    public String getState() { return state; }
    public void setState(String v) { this.state = v; }
    public String getCountry() { return country; }
    public void setCountry(String v) { this.country = v; }
    public String getPostalCode() { return postalCode; }
    public void setPostalCode(String v) { this.postalCode = v; }
    public String getPhone() { return phone; }
    public void setPhone(String v) { this.phone = v; }
    public String getFax() { return fax; }
    public void setFax(String v) { this.fax = v; }
    public String getEmail() { return email; }
    public void setEmail(String v) { this.email = v; }
    public Integer getSupportRepId() { return supportRepId; }
    public void setSupportRepId(Integer v) { this.supportRepId = v; }

    @Override
    public String toString() {
        return "Customer{id=" + customerId
                + ", name='" + firstName + " " + lastName + "'"
                + ", email='" + email + "'}";
    }
}
model/CustomerContact.java
package com.example.musicstore.model;

public class CustomerContact {
    private String firstName;
    private String lastName;
    private String email;
    private String city;
    private String country;

    public CustomerContact() {}

    public String getFirstName() { return firstName; }
    public void setFirstName(String v) { this.firstName = v; }
    public String getLastName() { return lastName; }
    public void setLastName(String v) { this.lastName = v; }
    public String getEmail() { return email; }
    public void setEmail(String v) { this.email = v; }
    public String getCity() { return city; }
    public void setCity(String v) { this.city = v; }
    public String getCountry() { return country; }
    public void setCountry(String v) { this.country = v; }

    @Override
    public String toString() {
        return "CustomerContact{name='" + firstName + " " + lastName + "'"
                + ", email='" + email + "'}";
    }
}

After creating these files, verify the cluster is running:

docker exec gridgain9-node1 /opt/gridgain9cli/bin/gridgain9 sql \
  "SELECT COUNT(*) AS tracks FROM Track;"

Expected result: 3503. If you need to restore the cluster or reload the dataset, see the full restore instructions in Start Your Local GridGain 9 Development Cluster.

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 runInTransaction simplifies lifecycle management with auto-commit, auto-rollback, and auto-retry

  • How to run transactions asynchronously with runInTransactionAsync and CompletableFuture

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

GridGain read-write transactions use SERIALIZABLE isolation. Locks are acquired on first access and held until commit or rollback. No other read-write transaction can modify the same rows while the lock is held. Read-only transactions use snapshot isolation instead. They see a consistent point-in-time view of the data without acquiring locks.

The Customer and Invoice tables are a colocated pair. The schema uses CustomerId as the colocation key for Invoice, so an invoice lands in the same partition as its customer. InvoiceLine uses InvoiceId as its colocation key, which keeps all lines of one invoice in the same partition but does not place them with the Invoice row or the Customer row, because colocation does not chain through a middle table. When a transaction writes only rows that share a partition, such as all lines of one invoice, all lock acquisitions happen on the same node, eliminating network round-trips between nodes for each operation. The benefit is latency reduction at scale: fewer distributed coordination steps per transaction.

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.

TransactionOptions controls three settings when passed to client.transactions().begin():

  • timeoutMillis(long): How long the transaction waits before automatically rolling back (default: 30 seconds). Set this lower for time-sensitive workflows where a stalled transaction should fail fast.

  • readOnly(boolean): When true, the transaction uses snapshot isolation instead of SERIALIZABLE, acquiring no locks. Read-only transactions are faster for analytics queries that do not modify data.

  • label(String): A diagnostic string visible in the SYSTEM.TRANSACTIONS system view. Use labels in production to identify transaction types during troubleshooting.

See Performing Transactions for the full TransactionOptions reference.

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:

Pattern
Choose when

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?