Work With RecordView and KeyValueView
Master both Table API view types: CRUD operations, bulk processing, cache-aside patterns, and the unified storage model that eliminates separate caching infrastructure.
Introduction
In the previous tutorial, you connected a Java application to the cluster and used RecordView and KeyValueView for basic reads and writes. You saw that both views access the same underlying data. Now you learn the full operation set and discover something more significant: KeyValueView gives you cache-like semantics backed directly by the system of record.
In a traditional architecture, you maintain a cache (Redis, Memcached) alongside your database and write invalidation logic to keep them synchronized. That synchronization is a source of bugs, staleness, and operational complexity.
With GridGain, there is no separate cache. A put through KeyValueView writes to the same distributed storage that SQL queries read. There is nothing to invalidate.
This tutorial starts with the API mechanics (operations, conditionals, bulk processing), moves to multi-column tables and partial POJO mapping, then pivots to the caching patterns that make this architecture practical.
Prerequisites
A running 3-node cluster with the Music Store dataset from Start Your Local GridGain 9 Development Cluster
Completed Connect with the Java Thin Client (familiarity with the thin client, Maven project setup, and RecordView basics)
Java 17 or later
Maven 3.8 or later
What You Will Learn
How to perform single-record and bulk operations with RecordView
How to access tables as key-value pairs with KeyValueView
How both views share the same underlying data
How to map partial POJOs to wide tables for efficient access
How to use KeyValueView as a cache backed by the system of record
When to choose RecordView vs KeyValueView for your use case
What You Will Build
A structured Java project with domain model classes and a series of exploration classes that exercise the full RecordView and KeyValueView operation set against the Music Store dataset. The model package holds 3 stable POJO classes that map to cluster tables. Each step creates a new Java class file in the main package, so your previous code stays in the project for reference. You end up with 8 exploration classes plus the 3 model classes.
The progression starts with API mechanics on the 2-column Artist table. It then moves to partial POJO mapping on the 13-column Customer table. The final steps cover cache-aside patterns that show why GridGain's unified model eliminates the need for a separate caching layer. All write operations use Artist IDs above the existing dataset range and clean up after themselves.
Set Up the Project
Create a new project directory and set up a Maven project with the GridGain thin client dependency. The structure is the same as the previous tutorial.
The group ID is org.gridgain, but the artifact name keeps the ignite- prefix. All Java packages remain org.apache.ignite.*.
Create the source directories:
The model package holds your domain classes. These are stable artifacts that don't change as you explore different API operations. The Artist class maps to the existing Artist table in the cluster. Field names match column names (case-insensitive), and the no-arg constructor is required for GridGain to deserialize rows from the cluster.
Now create ConnectAndVerify.java:
The project has two source files: the Artist model in the model package and ConnectAndVerify as the first exploration class. The model classes are stable artifacts that map your domain to the cluster. Each subsequent step creates a new Java class in the main package, so your previous code stays in the project for reference.
Run the application:
RecordView Single-Record Operations
You can read an existing artist by key. Now work through the full set of single-record write operations. Each operation has different semantics for handling existing and missing records, and the distinction matters when multiple threads or services access the same data.
All write operations in this step use ArtistId values starting at 10001, safely above the 275 existing Music Store artists.
Create RecordViewOps.java in the same package:
Run the application:
Each step creates a new class and uses the -Dexec.mainClass flag to run it. Your previous step's code remains in the project for reference.
Three distinct write strategies emerged from that output:
upsert always succeeds. It inserts a new row or overwrites an existing one. This is the right choice when you want idempotent writes and don't care whether the record existed before.
insert is the create-only counterpart. It returns true when it creates a new row and false when the key already exists. The existing row is never touched. In concurrent systems, insert prevents one thread from silently overwriting data written by another.
replace is the update-only counterpart. It returns true when it updates an existing row and false when the key is missing. It never creates a new row. Use replace when updating a record that should already exist: a missing row means something unexpected happened.
getAndDelete retrieves and removes a record in a single atomic operation. The returned Artist contains the data as it existed immediately before deletion. After the call, get() for the same key returns null. This is useful for queue-like patterns where you need the data one last time before removing it.
All operations pass (Transaction) null for the transaction parameter. The explicit (Transaction) cast ensures the code compiles across all GridGain 9 versions. The null value means each operation runs in its own implicit transaction. Explicit transactions are covered in the next tutorial.
RecordView Bulk Operations
Single-record operations make one network round-trip per call. When you need to process multiple records, bulk operations send all of them in a single request. The cluster handles routing each record to the correct partition internally.
Create BulkOps.java:
Run the application:
Key details in this code:
upsertAllwrites all 5 records in a single network request. The cluster routes each record to the node that owns its partition. Compared to 5 individualupsertcalls, this is one round-trip instead of five.getAllreturns a collection with one entry per input key. Keys that exist produce their correspondingArtistobject; keys that do not exist producenull. The code filters nulls to count only the records that were found. This behavior differs from KeyValueView'sgetAll, which you see in the next step.deleteAllreturns a collection of records that were not deleted (because they did not exist). An empty return collection means every key was found and removed.
KeyValueView Operations
RecordView maps each table row to a complete POJO. KeyValueView offers an alternative: it splits each row into a separate key type and value type, providing a Map-like interface to the same underlying data.
For the Artist table with its two columns (ArtistId and Name), KeyValueView<Integer, String> maps the primary key column to Integer and the single non-key column to String. The table is the same; only the API shape changes.
Create KeyValueViewOps.java:
Run the application:
The KeyValueView operation names differ from RecordView, but the semantics are identical:
put
upsert
Insert or update (idempotent)
putIfAbsent
insert
Create only, returns false if key exists
replace
replace
Update only, returns false if key missing
remove
delete
Remove by key, returns true if found
putAll
upsertAll
Batch insert or update
getAll
getAll
Batch read by keys
removeAll
deleteAll
Batch remove by keys
Notice how get(1) returned the string "AC/DC" directly, not an Artist POJO. KeyValueView strips away the object wrapper and gives you just the value column.
One behavioral difference to note between the two getAll calls:
KeyValueView.getAllreturns aMapcontaining only the keys that were found. The missing key (10099) is absent from the result.RecordView.getAllreturns a collection that includesnullentries for missing keys, in the same order as the input keys.
To detect missing records, filter nulls from the RecordView collection or call Map.containsKey on the KeyValueView result.
Both Views, Same Data
The previous steps used RecordView and KeyValueView in separate applications. In practice, you use both views in the same application, sometimes on the same table within the same method. A write through one view is immediately visible through the other because both are wrappers over the same distributed storage.
Create CrossView.java:
Run the application:
Both views return a reference to the same table from client.tables().table("Artist"). The recordView() and keyValueView() calls create client-side wrappers over the same underlying data. A row upserted through RecordView is immediately readable through KeyValueView, and a value written through KeyValueView appears in the next RecordView read.
This has a practical consequence: you can use RecordView for writes (where the full POJO is natural) and KeyValueView for reads (where you only need one column), mixing both in the same service without synchronization.
Multi-Column Tables With Partial POJOs
The Artist table has only two columns, so KeyValueView<Integer, String> maps one-to-one. Real applications have tables with many columns. The Customer table has 13 columns, including address, phone, email, and support representative fields. This is where the two views diverge meaningfully.
Just as you created Artist.java in the model package in Step 1, add two new model classes for the Customer table. The first maps all 13 columns; the second maps only 5 contact-related columns.
Create model/Customer.java:
Create model/CustomerContact.java for the partial 5-column mapping:
Now create PartialPojos.java:
Run the application:
Both views return the same Customer 1 row, but the code structure reveals two different approaches:
RecordView uses a single
CustomerPOJO with all 13 fields.customerIdis part of the object. This is natural when your code works with complete customer records.KeyValueView separates the key (
Integerfor CustomerId) from the value (CustomerContactPOJO). TheCustomerContactclass maps only 5 of the 12 non-key columns:firstName,lastName,email,city, andcountry. GridGain matches POJO fields to table columns by name. Columns not represented in the POJO (company,address,state,postalCode,phone,fax,supportRepId) are skipped on reads. Do not use this partial POJO to write: aputsends a full row, so the unmapped columns are set to their defaults (NULL unless the column has aDEFAULT).
This partial mapping is the key advantage of KeyValueView on wide tables. A service that only needs contact information defines a 5-field POJO instead of mapping all 13 columns. The smaller object reduces memory overhead per record and makes the code's intent explicit: this code path cares about contact data, not the full customer record.
Cache-Aside With KeyValueView
You have been using KeyValueView as a table access API. Now look at it from a different angle: KeyValueView is also a cache interface backed by the system of record.
In a traditional architecture, the cache-aside pattern works like this: check the cache (Redis), miss, query the database, write the result to the cache, serve the response. Two systems, two networks, and an invalidation strategy to keep them synchronized. Every write must update both the database and the cache, or stale data creeps in.
With GridGain, the "cache" and the "database" are the same storage:
kvView.get()reads a row from distributed storage by primary key.kvView.put()writes a row to that same distributed storage.SQL queries read the rows written through either view.
There is no separate layer to synchronize and nothing to invalidate.
Create CacheAside.java:
Run the application:
The SQL query at ArtistId 10001 returned "Cache Populated Artist", the exact value written through putIfAbsent. This is the architectural point: there is no cache-to-database synchronization because there is no separation. The KeyValueView write and the SQL read access the same distributed storage.
Key operations for cache patterns:
get()is the cache read.nullmeans the data does not exist in the system, not just in the cache. There is no "cache miss" that requires a fallback to a separate database.getAll()is the batch warm-up. Pre-load a set of hot keys at application startup in one network round-trip. In a Redis-based architecture, this would be aMGETfollowed by conditionalSETcalls for misses. Here, the data is already in the system of record.putIfAbsent()is the conditional population. It writes only if the key does not exist, which prevents concurrent threads from overwriting each other. This is equivalent to RedisSETNXbut with ACID guarantees and no separate cache layer.contains()checks whether a key exists without deserializing the value. This is useful for membership testing (does this session exist? is this user active?) without the overhead of fetching the full record.
Production Caching Patterns
The previous step demonstrated the cache-aside pattern against existing Music Store data. This step shows three production patterns that replace infrastructure you would otherwise build with a separate caching system.
Create CachePatterns.java:
Run the application:
Each pattern replaces a piece of caching infrastructure:
Batch warm-up (
getAll) replaces the startup script that queries your database and populates Redis. The data is already in the distributed store.getAllis a single round-trip that confirms which keys are available and returns their values.Atomic read-and-remove (
getAndDelete) replaces RedisLPOPfor queue patterns. The record is read and removed in one atomic operation. No race condition between the read and the delete.Multi-get (
getAllon RecordView or KeyValueView) replaces RedisMGET. Resolve a batch of IDs to full objects or key-value pairs in one round-trip. The cluster routes each key to the correct node internally.
In all three patterns, the data is authoritative. There is no stale cache to worry about, no TTL to tune, and no invalidation logic to debug.
GridGain 9 Near-Cache
The patterns in the previous two steps eliminate the need for a separate caching system. Every get() call still makes a network round-trip to the cluster. For hot data that your application reads thousands of times per second, that round-trip adds up.
GridGain 9 adds NearCacheOptions to both RecordView and KeyValueView. The near-cache stores recently accessed records in the client JVM's memory. Repeated reads of the same key serve from local memory without a network round-trip.
Key configuration options:
maxEntrieslimits the number of cached records. When the limit is reached, the least recently accessed entry is evicted. Default: 0 (no limit).expireAfterAccesssets the TTL in milliseconds after the last read. Entries not accessed within this window are evicted. Default: 5000ms (5 seconds).expireAfterUpdatesets the TTL after a write. Use this when you want writes to refresh the TTL. Default: 5000ms (5 seconds).
The defaults matter: a near-cache created without explicit TTL values expires entries after 5 seconds. The code example above sets expireAfterAccess to 10 seconds to keep hot entries longer.
The near-cache is a read-through cache: when a key is not in the local cache, the get() call fetches from the cluster and populates the cache automatically. Writes through the same view go to the cluster and invalidate the local entry, so the next read through the view fetches the new value. A view with a near-cache does not accept explicit transactions: passing a transaction throws UnsupportedOperationException.
Near-cache also works on RecordView. The same Mapper.of() pattern applies:
Choose the Right View
Both views access the same underlying data. The choice depends on your access pattern, not your data model.
CRUD on domain objects (all columns)
RecordView
Type-safe POJOs, natural object-oriented code
Lookup by key, return a subset of columns
KeyValueView
Partial POJO maps only the columns you need
Cache-like patterns (has key? get value)
KeyValueView
Map-like API: get, put, contains
Complex records with many columns
RecordView
One POJO maps the full row
High-frequency lookups on hot data
KeyValueView + near-cache (GG9)
Client-side cache eliminates network round-trips
Batch loading or warm-up
Either (bulk ops)
RecordView upsertAll for full rows; KeyValueView putAll for key-value pairs
Queue-like processing
RecordView
getAndDelete provides atomic read-and-remove
Production applications commonly use both views on the same table. A service might use RecordView for full CRUD operations during data ingestion and KeyValueView for fast lookups in the request path. The views are complementary, not competing.
The operational semantics are identical across both views. An insert through RecordView and a putIfAbsent through KeyValueView enforce the same create-only guarantee. A deleteAll through RecordView and a removeAll through KeyValueView return the same information (keys that were not found). Choose based on the shape of data your code works with: full objects or key-value pairs.
Summary
You exercised the full RecordView and KeyValueView operation set across two Music Store tables: Artist (2 columns) for API mechanics and Customer (13 columns) for partial POJO mapping. Three write strategies (idempotent, create-only, update-only), bulk operations for throughput, and cross-view data sharing established the API foundation.
The caching steps revealed the architectural advantage: KeyValueView provides cache-like semantics (get, put, putIfAbsent, contains, getAll) backed directly by the system of record. There is no separate cache layer to synchronize, no invalidation logic to write, and no stale data to debug. A putIfAbsent through KeyValueView and a SELECT through SQL read from the same distributed storage. GridGain 9's near-cache adds client-side caching with TTL for hot read paths.
All operations in this tutorial used implicit transactions (the null transaction parameter). The next tutorial, Use Transactions in GridGain 9, introduces explicit transactions: grouping multiple operations into an atomic unit so they succeed or fail together.
Related
Start Your Local GridGain 9 Development Cluster for the cluster setup and dataset this tutorial connects to
Connect with the Java Thin Client for the thin client connection patterns and Table package hierarchy
How to Configure Logging for the Java Thin Client for controlling log output in your application
This page is: Copyright © 2026 MariaDB. All rights reserved.
Last updated
Was this helpful?

