From Key-Value to SQL: The JOIN Problem
Move beyond client-side joins. Annotate POJOs with @QuerySqlField, run SqlFieldsQuery on cached data, and use colocation for fast cross-cache JOINs.
Introduction
A customer support screen shows every invoice for a given customer. A monthly report pulls all orders billed from Brazil. Each screen starts with something you know (a customer ID, a country name) and returns records whose keys you do not know.
Cache API lookups need keys you already have. The Cache API can push a single-cache predicate to the server with ScanQuery and IgniteBiPredicate, and cache.iterator() can return every entry for client-side filtering. Neither helps when the question is "invoices joined to their customers filtered by country and grouped by month." This tutorial teaches the same caches to answer the harder questions with SQL: you load the Chinook music-store dataset (59 customers, 412 invoices) into two caches, ask one concrete question three ways, and finish with a cross-cache JOIN whose EXPLAIN plan shows how colocation keeps the JOIN local.
Prerequisites
A running single-node cluster from Start a Local Cache Development Cluster
Cache API familiarity from Work with the Cache API
Java 17 or later for the client runtime
Maven 3.6 or later
Docker Compose 2.23 or later
This tutorial builds a fresh Maven project called sql-on-cache/. It does not extend the cache-client/ project from the Foundations path because the SQL engine needs the ignite-indexing dependency that the Cache API tutorials did not use.
What You Will Learn
In this tutorial, you:
Annotate POJOs with
@QuerySqlFieldso the cache knows which fields are SQL columnsConfigure two caches with
setIndexedTypesto register the SQL schema from the annotationsSeed the caches from a Chinook dataset file using SQL
INSERTstatements throughSqlFieldsQueryAnswer "find all invoices for customer 17" with the Cache API alone and watch the client-side scan do the wrong thing
Replace the scan with a parameterized
SqlFieldsQueryand see the filter run server-side on an indexRun a cross-cache JOIN between Customer and Invoice and read the H2 EXPLAIN plan that confirms it stayed local
Define the Queryable Schema
Three POJOs carry the schema: Customer, Invoice, and the composite InvoiceKey. Annotations on their fields tell the cache which columns exist, which ones are indexed, and which one drives partitioning.
Create a Maven project called sql-on-cache/. The pom.xml adds two things the Foundations path did not need: the ignite-indexing dependency that brings the H2 SQL engine onto the classpath, and an extra --add-opens entry so the optimized marshaller can read java.sql.Date.
Create the three model classes under src/main/java/com/example/sqlquery/model/:
Three fields, three @QuerySqlField annotations. Every annotated field becomes a SQL column with the same name as the field. Fields without the annotation are still stored on the cache entry, but they are invisible to SQL and cannot appear in SELECT column lists or WHERE predicates. The customerId is the cache key here, not a field. SQL references the cache key through a pseudo-column called _key, which the cross-cache JOIN later in this tutorial uses in its join predicate.
The Invoice POJO carries the fields that change per invoice: the date, the billing country, and the total. It does not carry invoiceId or customerId. Both of those fields live on the composite key class because the cache key in the Invoice cache is a composite of (invoiceId, customerId). Putting customerId on the key lets one annotation do two jobs: drive partitioning so customer 17's invoices live on the same node as customer 17, and expose the field as a SQL column so queries can filter on it.
InvoiceKey is the most concept-dense class in the tutorial. Three annotations across two fields encode three separate decisions:
@QuerySqlFieldoninvoiceIdsurfaces the field as a SQL column. Without the annotation,SELECT invoiceId FROM Invoicefails withColumn "INVOICEID" not found.@QuerySqlField(index = true)oncustomerIddoes two things at once: surfaces the column to SQL, and tells the SQL engine to maintain an index on it. Queries later in this tutorial filter on this column, and the index is what makes those queries an index scan rather than a table scan.@AffinityKeyMappedoncustomerIdis the colocation declaration. The cache partitions entries by hashing this field, which places every invoice on the same node as the customer whose ID matches. The cross-cache JOIN relies on this.@AffinityKeyMappedalone does not expose the field to SQL, and@QuerySqlFieldalone does not influence partitioning. Both annotations stack on the colocation key so it does both jobs.
Configure the Caches and Seed the Dataset
The caches need QueryEntity descriptions built from the annotations. After they exist, the Chinook dataset loads into them: 59 customers and 412 invoices.
Create ConfigureCaches.java in com.example.sqlquery:
Compile and run:
Expected output:
Two caches exist. Both have QueryEntity descriptions built from the POJO annotations. Both are ready to accept SQL.
Now populate them. Download the dataset file into the sql-on-cache/ directory so it sits next to the pom.xml:
SeedFromChinook reads the file relative to the JVM's working directory, which is also sql-on-cache/ when you run Maven from there.
The file contains 59 Customer INSERTs and 412 Invoice INSERTs, trimmed from the full Chinook music-store schema to the columns this tutorial queries. The dates use H2's parsedatetime() function because the cached SQL engine is H2.
Create SeedFromChinook.java in the same package:
Run it:
Expected output:
SqlFieldsQuery runs DML, not just SELECT. The count queries also confirm that SQL and the Cache API share one storage. Rows inserted via SQL are the same entries cache.get(1) returns as a Customer POJO.
The Client-Side Filter
The caches hold 59 customers and 412 invoices. Consider the question that opened this tutorial: "find all invoices for customer 17." You know customerId = 17. You do not know the invoice IDs.
The Cache API has two iteration paths. cache.iterator() returns every entry to the client and the filter runs in Java. cache.query(new ScanQuery<>(predicate)) pushes a single-cache IgniteBiPredicate to the server so only matches cross the network. This step uses the first path so the cost of pulling every entry is visible. Later steps move to SQL when the question outgrows a single-cache predicate.
Create ClientSideFilter.java:
Run it:
Expected output:
The invoice dates match the parsedatetime values in the dataset file. A client JVM in a time zone behind the server's can show them one day earlier, because java.sql.Date prints in the client's zone.
Customer 17 has seven invoices, all from the USA. The scanned-count line makes the cost visible: 412 entries crossed the wire, 405 were thrown away. Scale that ratio to millions of entries and the JVM runs out of heap before the scan finishes.
The Cache API can push a server-side predicate over a single cache with ScanQuery and IgniteBiPredicate, which would skip the wasted-entry shipping shown above. What the Cache API cannot do is join two caches in one query, run an aggregation, or accept the composable typed predicates a column-aware engine offers. The annotations you added in the last step gave the cache another way to answer those questions: SQL.
SQL on one Cache
Create IndexedQuery.java. The class runs three queries against the Invoice cache: a parameterized lookup by the indexed customerId, a two-predicate scan, and an aggregation.
Run it:
Expected output:
Query 1 returned the same seven invoices as the client-side scan, but the filter ran on the server against the customerId index. Only matching rows crossed the wire, and the ORDER BY invoiceDate clause also ran server-side.
Query 2 applied two predicates. Neither billingCountry nor total has an index, so H2 scans the Invoice data and applies both conditions as filters during the scan. The predicates compose at the SQL layer in one statement. A Cache API version would need a custom loop evaluating both conditions per entry.
Query 3 is the biggest shift. The cache computed COUNT(*), SUM(total), and MAX(total) for the seven matching invoices and returned one row with three columns. The Cache API has no cache.count(predicate) or cache.sum(field, predicate). Aggregations are a SQL-only surface.
Cross-Cache JOIN With Colocation
The next question spans two caches: which Brazilian customers have spent the most in total? Country lives on the Customer cache. Invoice totals live on the Invoice cache. One JOIN answers both.
@AffinityKeyMapped on InvoiceKey.customerId already aligns the two caches so each customer's invoices live on the same partition as the customer record. The JOIN below uses that alignment, and the EXPLAIN plan after confirms it.
Create ColocatedJoin.java:
Run it:
Expected output:
Five Brazilian customers ranked by lifetime spend. Luís Gonçalves at $39.62 leads by a narrow margin. The other four tie at $37.62 because their Chinook purchase histories are nearly identical.
The EXPLAIN block shows two distinct SQL statements separated by the second SELECT. That structure is how distributed SQL executes. The first statement is the map phase that runs locally on each partition. The second statement is the reduce phase that runs at a single coordinator to merge the partial results. Read each block separately.
Map phase (runs on each partition):
FROM "Invoice"."INVOICE" "I__Z1"scans the local Invoice partition with the comment/* Invoice.INVOICE.__SCAN_ */. The scan is a full read of the partition. This plan does not use theINVOICEKEY_CUSTOMERID_IDXindex.INNER JOIN "Customer"."CUSTOMER" "C__Z0"with the comment/* Customer._key_PK: _KEY = I__Z1.CUSTOMERID */looks up each invoice's customer in the Customer primary-key index. The lookup column is_KEY, the cache key, and it matches the invoice's affinity fieldcustomerId. That match is what makes the lookup local: the customer row sits in the same partition as the invoice. TheCOUNTRY = ?1predicate is applied to the rows the lookup returns.The critical absence is anything saying "distributed" or "broadcast." The JOIN runs on each partition against the partition's local Invoice and Customer rows. No data moves between partitions.
Reduce phase (runs at the coordinator):
FROM "PUBLIC"."__T0"with the comment/* Customer.merge_scan */is the synthetic table that holds the partial aggregates from every partition's map phase. The coordinator groups them again and produces the final result. Because each partition only sends one small aggregate, the reduce phase stays cheap even for large tables.
Summary
You added two annotations and two new calls to a cache you already knew how to use. The cache went from "key lookups only" to "full SQL surface with indexes, aggregations, and cross-cache JOINs."
The shape of the question selects the interface. Lookups by a known key keep using cache.get at in-memory speed. Any predicate on a non-key field, any aggregation, any filter composition, and any JOIN uses SqlFieldsQuery. Both views exist on the same cache, over the same data. The choice is not a storage strategy. It is a query strategy made per call site.
Colocation is a schema-design decision, not a runtime one. Without colocation, a JOIN between two caches returns incomplete results unless you enable setDistributedJoins(true), and with the flag on the cost differs by orders of magnitude because rows move between nodes. @AffinityKeyMapped on the right key turns the JOIN into a local per-partition operation that scales with the number of partitions rather than the size of the data moved between them. Make the colocation decision when you define the cache, not when the query gets slow.
The deeper reframing is that the cache is a distributed database with two access surfaces. Key-value access handles single-key hot paths at in-memory speed. Everything else, filters, aggregations, JOINs, uses SqlFieldsQuery against the same data. One annotation on the POJO and one setIndexedTypes call replace the need for a separate query database alongside the cache.
What's Next
setDistributedJoins(true)for the case where colocation is not possible, covered in When to Break Colocation.Secondary indexes and composite (group) indexes. See Defining Indexes.
DDL-based cache creation (
CREATE TABLE ... WITH "CACHE_NAME=..., VALUE_TYPE=..."), the alternative path that creates caches from SQL instead of Java configuration. See SQL and Key-Value Usage.
The next tutorial in this learning path, Atomic Operations Across Keys: The Transaction Problem, shifts from queries to writes. Cross-partition transactions solve the problem of atomically updating two keys that live on different nodes, a case single-shard txStart() does not cover.
Related
Use Transactions with the Cache API covers the atomicity tools that let multi-key writes succeed or fail together on a single partition.
Cache-Aside Under Load covers the mediation pattern where the cache sits in front of a source-of-truth database.
This page is: Copyright © 2026 MariaDB. All rights reserved.
Last updated
Was this helpful?

