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

Choose the Right Data Access Pattern

Build a data access layer that selects KeyValueView, RecordView, or SQL at every call site based on key availability, operation shape, and safety requirements.

Introduction

The entity classes from the previous tutorial carry two responsibilities: they define the schema, and they map fields to columns at runtime. The @Id annotations that declared composite primary keys for colocation have a third effect that surfaces the moment your application makes its first data access call. Those annotations constrain which API calls are possible, which write operations are safe, and which consistency guarantees are available.

In this tutorial, you build a data access layer for the Music Store: nine service methods, each selecting its API based on key availability, operation shape, and safety requirements.

GridGain 9 provides the RecordView, KeyValueView, SQL, and transaction APIs used in this tutorial, and adds near-cache for client-side caching, covered in a dedicated section at the end.

Prerequisites

Returning to these tutorials? Verify your environment.

Check that the cluster is running and the Music Store data is loaded:

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

Expected result: 3503. If the query succeeds, your environment is ready.

If the containers are stopped, restart them from the directory containing your docker-compose.yml:

docker compose up -d

Data persists across restarts. Wait 15-30 seconds for the nodes to rejoin, then re-run the check above.

If the cluster was destroyed (docker compose down), start the containers and re-initialize. See Start Your Local GridGain 9 Development Cluster for the full setup process.

What you Will Learn

  • Why RecordView and KeyValueView require the full composite primary key for point lookups

  • How to select the right API based on key availability, operation shape, and safety needs

  • When to use insert instead of upsert for write safety

  • How to mix RecordView, KeyValueView, and SQL in a single transaction

  • How to evaluate the near-cache consistency tradeoff (GridGain 9)

Set Up the Project

Create a new Maven project in your IDE. This is a separate project from the annotations tutorial. A fresh project avoids dependencies on any modifications you may have made, and the entity classes are portable because the annotations carry the schema definition with the class.

Replace the generated pom.xml with the following:

GridGain 9 artifacts are published to the GridGain external Nexus repository, not Maven Central. The <repositories> block is required for all GridGain 9 projects.

Copy four entity classes from the annotations tutorial into a model package (src/main/java/com/example/musicstore/model/): Artist, Album, Customer, and Invoice. These are the tables the service class operates on through the programmatic APIs. SQL queries reference other tables (Track, InvoiceLine) by name without needing entity classes.

As you paste each class, count the @Id annotations. Artist has one. Album has two. Customer has one. Invoice has two. That count determines what your application must provide for every programmatic data access call.

Entity classes (copy from the annotations tutorial)

Discover the Composite Key Constraint

You need to display Album 5 on a detail page. You know the AlbumId from the URL, but not the ArtistId. Try looking it up through RecordView, the same way the foundations tutorials accessed single-key tables.

Create ExploreKeys.java in the com.example.musicstore package:

Run ExploreKeys. The first output is the most important:

Album 5 exists. You loaded it in the annotations tutorial. But the partial-key call never reaches the cluster.

The client's MarshallerException tells you exactly what went wrong: ArtistId is null, and the @Column(nullable = false) annotation on that @Id field prohibits it.

This is three design decisions converging into one exception. In the schema tutorial, you made ArtistId the colocation column for Album. That required ArtistId in the composite primary key. In the annotations tutorial, you marked every @Id field with @Column(nullable = false) because PK columns cannot be nullable. Now, at runtime, the marshaller enforces that annotation before the request leaves the client.

KeyValueView throws the same exception class with a different message ("Missed key column") because the Tuple marshaller checks for missing key columns explicitly rather than checking nullable constraints. Both reject the request before it reaches the cluster. The error messages differ, but the constraint is the same: the schema's composite primary key requires all key columns.

Open Album.java in your IDE and count the @Id annotations. Two: albumId and artistId. Every RecordView and KeyValueView operation on this table needs both values. Now open Artist.java. One @Id. Artist lookups need only one value. The number of @Id annotations on a class tells you how many fields your application must provide for a point lookup.

The EXPLAIN plans reveal what SQL does differently. These are the same three routing behaviors from the schema tutorial, but the question has shifted from how the engine routes a query to which API your application should use.

The planner chooses between the secondary index and a table scan using table statistics. On a freshly loaded cluster, before statistics are collected, the ArtistId query can show a TableScan instead of the IndexScan above.

Three queries on the same table produce three different routing strategies:

  1. Full primary key: the engine performs a direct KeyValueGet to the exact partition.

  2. Colocation column only (ArtistId): the engine uses the secondary index on the colocation column. Because the colocation column is known, it can target the partition that holds the artist's albums.

  3. Non-colocation column only (AlbumId): the engine scans all partitions because it cannot determine which node holds the data without the colocation column.

SQL accepts any column combination in a WHERE clause. RecordView and KeyValueView require the full primary key. When your caller does not have the full key, SQL is the only option.

Create the Service Class

The exploration showed three situations where different APIs are the right choice: RecordView and KeyValueView for point lookups with the full key, SQL for everything else. A realistic data access layer holds references to all three and selects the API at each call site based on the operation.

Create MusicStoreService.java in a service package (src/main/java/com/example/musicstore/service/):

The constructor obtains four RecordView references, one KeyValueView, the SQL interface, and the transaction manager. Keeping all view types in one class makes the API comparisons visible side by side. A production application would typically separate by domain boundary: a CatalogService for artists and albums, a CommerceService for invoices and customers.

Implement Read Methods

A sidebar displays the artist name next to each album listing. The caller knows the ArtistId and needs only the name, not the full Artist record. Add this method to MusicStoreService.java after the customerKey helper:

A user clicks an album to see its details. The page URL encodes both the AlbumId and ArtistId. Add the next method below getArtistName:

A user browses AC/DC's discography. The application knows the ArtistId but not the AlbumIds. RecordView and KeyValueView cannot help because Album requires both key columns. SQL handles any column combination in a WHERE clause. Add findAlbumsByArtist below getAlbum:

A customer shares an album link. The URL contains only the AlbumId. Without the colocation column, the engine cannot determine which partition holds this album, so it scans all partitions. This full scan is the tradeoff for optimizing Artist-to-Album colocated joins: browsing by artist (the common case) is fast, while direct album-by-ID lookups (the rare case) cost more. Add findAlbumById next:

A dashboard shows the top-selling tracks across the entire catalog. This query joins four tables that cross colocation boundaries: InvoiceLine to Track to Album to Artist. Each of the first three is colocated by a different column (InvoiceId, AlbumId, ArtistId), and only the Album-Artist pair is colocated with each other. No programmatic API supports joins. Add getTopSellingTracks as the last read method:

Five read methods, and the pattern is already visible:

  • Full primary key, one field: KeyValueView returns the value without deserializing the full entity.

  • Full primary key, whole entity: RecordView returns the typed POJO with every mapped field.

  • Partial key with the colocation column: SQL reaches a single partition because the engine knows where the data lives.

  • Partial key without the colocation column: SQL scans all partitions because the engine has no routing hint.

  • Join across tables: SQL is the only option, and colocation decides whether rows stay on their nodes or cross the network.

Verify your progress by adding a temporary main method to MusicStoreService (or a quick test class) that calls the first two methods:

Expected output:

Implement Write Methods

Write operations add a second dimension to API selection: beyond which API can reach the data, what safety guarantees does the operation require? The next four methods each demonstrate a different answer. Continue adding them to MusicStoreService.java below the read methods.

An editor corrects a typo in an album title. The application has both the AlbumId and ArtistId, so RecordView is technically possible. But the operation touches a single column. RecordView would need a get-modify-upsert cycle: fetch the entire Album, change the title, write the whole object back. That is two network round-trips and a full-entity write for a one-column change.

This is the method that breaks the assumption that "full key means programmatic API." When the operation only touches a subset of columns, SQL does the job in one statement without loading the full entity. The shape of the operation overrides the routing answer.

An order arrives from the payment gateway. The application needs to create an invoice, but duplicate messages are possible. If the same invoice arrives twice, the second attempt must be rejected, not silently overwritten.

The foundations tutorials used upsert for every write. Here, insert is the right choice because the business logic demands duplicate detection. Two write methods exist on RecordView because they serve different safety requirements.

A checkout flow creates an invoice and updates the customer's billing address. Both operations must succeed or both must roll back. If the insert succeeds but the address update fails, the invoice references a stale address.

Every tutorial before this one passed null as the transaction parameter. This method shows why the parameter exists: when business logic demands that multiple operations succeed or fail together, an explicit transaction is the only way to guarantee it. The runInTransaction wrapper handles retry logic, so the application code stays focused on the business rule.

A personalization feature tags each customer with their favorite artist. This operation reads from one API and writes through another. The artist name is a single field (best served by KeyValueView), but the customer update needs all fields for validation before saving (RecordView).

Four write methods, and two distinct reasons why the "obvious" API choice was wrong:

  • updateAlbumTitle shows that the shape of the operation can override key availability. The full primary key was available, but SQL was still the right choice for a single-column write.

  • createInvoice writes a full entity through RecordView and uses insert for duplicate detection in an event-processing pipeline.

  • createInvoiceWithBillingUpdate also writes through RecordView, but wraps the work in an explicit transaction for multi-table atomicity.

  • updateCustomerWithArtistReference confirms that each call site within a single operation makes its own independent API decision. The read uses KeyValueView, the write uses RecordView.

Complete MusicStoreService.java (for verification)

Run and Verify All Methods

Create RunService.java to exercise every method and verify the results. Test data uses IDs above 9000 to avoid conflicts with the existing Music Store dataset. Each test cleans up after itself so you can run the program multiple times.

Run the program. Here is the expected output:

The findAlbumsByArtist and getTopSellingTracks results may appear in a different order on your cluster. SQL queries without an ORDER BY clause do not guarantee row ordering.

Walk through the output section by section:

The read methods show the three API paths in action. getArtistName returns a single string through KeyValueView. getAlbum returns a full POJO through RecordView, requiring both key columns. findAlbumsByArtist and findAlbumById both use SQL, but the colocation column determines whether one partition or all partitions are scanned. getTopSellingTracks joins four tables across colocation boundaries.

The updateAlbumTitle result confirms cross-API visibility: the SQL UPDATE writes the new title, and the subsequent RecordView get() reads it back. All three APIs operate on the same underlying storage. A write through one API is immediately visible to reads through any other API.

The createInvoice output shows the safety distinction. The first insert() returns true (new record created). The second call with the same key returns false (duplicate detected, no overwrite). Compare this to upsert(), which would silently overwrite the existing record without returning any signal.

The createInvoiceWithBillingUpdate result demonstrates an explicit transaction spanning two tables. The invoice insert and the customer address update either both commit or both roll back. The cleanup restores the original address so subsequent runs produce the same output.

The EXPLAIN plan at the bottom confirms the routing for findAlbumsByArtist: an IndexScan on IFK_ALBUMARTISTID within a single partition. The Exchange node with distribution: single is where the coordinator collects the rows. The IndexScan on IFK_ALBUMARTISTID with predicate: =(ARTISTID, 1) shows that the lookup uses the colocation column. The colocation decisions from the schema tutorial are visible in the query plan.

Open MusicStoreService.java in your IDE and use Find Usages on sql.execute. Every SQL call exists because the caller either lacked the full primary key or because SQL was more efficient for the operation's shape (the single-column update). Now search for albums.get and artistNames.get. Every programmatic API call exists because the caller had the full key and needed either the complete entity or a single field.

Near-Cache: Trading Consistency for Speed

GridGain 9 adds client-side caching through NearCacheOptions. A near-cached KeyValueView stores recently accessed entries in the client JVM's heap. The first read for a key fetches from the cluster; subsequent reads for the same key return from local memory until the time-to-live (TTL) expires.

The speed gain is real, but it comes with constraints that affect API selection.

Create NearCacheDemo.java in the com.example.musicstore package:

Run NearCacheDemo:

Exact timing values vary by machine and network conditions. The pattern is what matters: standard KeyValueView shows consistent network latency on every call, while near-cached KeyValueView drops to 0-1ms after the first fetch.

The staleness result is the critical observation. The second put writes "Updated Artist" through the standard view, but the cached view still returns "Test Artist" from its local cache. The cache entry stays until one of the expiry settings fires: expireAfterAccess (30 seconds in this configuration) or expireAfterUpdate (5 seconds by default, because this example does not set it), whichever comes first. Any other client that updates the same key is invisible to this view until the cache refreshes.

The transaction constraint is equally important. Passing a non-null Transaction to a near-cached view throws UnsupportedOperationException. If an operation needs transactional guarantees, it cannot use near-cache.

Near-cache is not a faster version of KeyValueView. It is a different consistency model. Standard KeyValueView guarantees that every get() returns the latest committed value. Near-cached KeyValueView guarantees that get() returns a value that was correct within the last N seconds. For artist names on a catalog page, 30 seconds of staleness is invisible to users. For an account balance in a transfer workflow, any staleness is dangerous.

The near-cache polling mode uses ContinuousQuery internally to receive change events from the server. ContinuousQuery is a GridGain 9 feature that provides real-time change notifications with event filtering, column projection, and watermark-based exactly-once resumption.

ContinuousQuery is also the change-capture primitive that powers the GG9 streaming stack: Kafka Connect source connectors stream table changes to Kafka topics. Data Center Replication copies data across clusters. Change Data Capture feeds changes to Apache Iceberg tables. All of these operate on the same tables and colocation columns you designed in the schema tutorials.

The Access Pattern Matrix

Nine methods, three APIs, and every choice was driven by the same three considerations: does the caller have the full primary key, what does the operation need, and what safety guarantees does it require. The matrix below maps each method to its decision:

Operation
Full Key?
What's Needed
Safety
API

Get artist name (sidebar)

Yes

One field (read)

Auto-commit

KeyValueView

Get album details (detail page)

Yes

Full entity (read)

Auto-commit

RecordView

Find albums by artist (browse)

No (colocation col)

Query result

Auto-commit

SQL (single partition)

Find album by ID (shared link)

No (non-coloc col)

Query result

Auto-commit

SQL (all partitions)

Top-selling tracks (dashboard)

No (join)

Aggregation

Auto-commit

SQL (crosses colocation boundaries)

Update album title (editor fix)

Yes

One column (write)

Auto-commit

SQL

Create invoice (order intake)

Yes

Full entity (write)

Create-only (dedup)

RecordView insert

Invoice + billing update (checkout)

Yes

Two-table write

Explicit transaction

RecordView in tx

Tag customer with artist (personalization)

Yes

Mixed read/write

Auto-commit

KV read + RV write

High-frequency artist lookup (GridGain 9)

Yes

One field (read)

Tolerates staleness

KV + near-cache

The Album table appears four times with four different APIs. The table does not determine the API. The call site does.

Look at the "Update album title" row. The full primary key is available, which makes RecordView possible. But the operation only changes one column, so SQL is more efficient. The shape of the write overrides the key availability.

Look at "Create invoice" and "Invoice + billing update." Both have the full key and write full entities. Without the safety column, both would be "RecordView with auto-commit." The safety requirement differentiates them: duplicate detection needs insert, and multi-table atomicity needs an explicit transaction.

The last row (GridGain 9 only) introduces a consistency tradeoff. Near-cache makes reads faster by accepting staleness and giving up transaction support. For stable reference data like artist names, this tradeoff is invisible to users. For rapidly changing data like account balances, it would be dangerous.

Every sync method in the service has an async counterpart (getAsync, putAsync, executeAsync). The API selection logic is the same for async operations. Bulk variants (upsertAll, putAll, getAll) follow the same full-key requirement.

Summary

What you Built

A data access layer with nine methods using KeyValueView, RecordView, and SQL on the same Music Store schema. Read methods, write methods, a transactional method, and a mixed-API method, each demonstrating a different combination of key availability, operation shape, and safety requirements.

Schema Design has Three Consequences

The schema tutorial established that schema design is performance design: colocation determines which queries are fast. The annotations tutorial expressed that design as code, with annotations carrying the schema alongside the application. This tutorial revealed two more consequences of those same decisions.

Colocation shapes your API options. Composite primary keys, created to enable colocated joins, require the full key for every RecordView and KeyValueView operation. When the caller does not have the full key, SQL is the only path. The number of @Id annotations on an entity class tells you what every programmatic call site must provide.

Safety requirements drive the final choice. Even when the full key is available and the operation shape fits RecordView, the business logic may demand insert instead of upsert (for duplicate detection), an explicit transaction (for multi-table atomicity), or SQL (for single-column writes that avoid a read-modify-write cycle). On GridGain 9, near-cache adds a consistency dimension: client-side speed at the cost of staleness and the loss of transaction support.

At every call site, three considerations determine the API: key availability, operation shape, and safety requirements. The colocation decisions made during schema design set the boundaries: they determine which API paths are available, which operations are efficient, and which safety guarantees are practical.

What's next: Stream Data with the Data Streamer API covers the maximum-throughput write path. Data Streamer provides at-least-once delivery with automatic batching and backpressure, building on the same schema and colocation columns.

This page is: Copyright © 2026 MariaDB. All rights reserved.

Last updated

Was this helpful?