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

Implement Schema With Java Annotations

Express distributed schema design decisions as Java annotations. Define entity classes, colocated table pairs, and distribution zones, then create the entire schema with a single API call.

Introduction

In the previous tutorial, you designed the Music Store schema in SQL DDL. That is the universal path. Every GridGain user, regardless of programming language, can create schemas with SQL. This tutorial adds a second path for Java developers. You define the same Music Store entities as annotated Java classes, and the catalog API reads the annotations at runtime and generates the exact DDL you wrote by hand.

Both paths produce identical schemas. The difference is where the design decisions live and what you get in return. DDL integrates with your operations workflow: migration tools, DBA-managed scripts, language-independent deployments. Annotations integrate with your Java development workflow: schema decisions visible in your IDE, type-safe data access through the same classes that defined the tables, and refactoring safety when column names change.

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:

docker compose up -d

Wait 10 seconds for the nodes to start, then load the license and initialize the cluster:

LICENSE=$(jq -Rs . gridgain-license.json)
curl -X POST http://localhost:10300/management/v1/cluster/init \
  -H "Content-Type: application/json" \
  -d '{"metaStorageNodes":["node1","node2","node3"],"cmgNodes":[],"clusterName":"my-cluster","license":'"$LICENSE"'}'

Download the schema and data files:

Copy the files into the container and load them:

docker cp music-store-schema.sql gridgain9-node1:/tmp/
docker cp music-store-data.sql gridgain9-node1:/tmp/
docker exec gridgain9-node1 /opt/gridgain9cli/bin/gridgain9 sql --file /tmp/music-store-schema.sql
docker exec gridgain9-node1 /opt/gridgain9cli/bin/gridgain9 sql --file /tmp/music-store-data.sql

The schema loader prints "Updated 0 rows" for each DDL statement. The data loader prints row counts per batch. Both commands emit jline reflection warnings that are cosmetic and safe to ignore.

Re-run the check above to verify 3503 tracks are loaded.

What You Will Learn

You define the full Music Store schema as annotated Java classes and create all tables from those annotations with a single API. Along the way you learn:

  • How six annotations (@Table, @Zone, @Id, @Column, @ColumnRef, @Index) express all distributed schema design decisions

  • How the catalog API generates CREATE ZONE, CREATE TABLE, and CREATE INDEX DDL automatically

  • How annotations relate to the catalog: annotations create the schema, the catalog owns it at runtime

  • Which schema features annotations cannot express and how to supplement with SQL DDL

Create the Project

Create a new Maven project in your IDE named music-store-schema. Replace the generated pom.xml with the following:

The ignite-client dependency includes the annotation API (org.apache.ignite.catalog.annotations) and the catalog DSL that translates annotations into DDL. No additional dependencies are needed.

Create two packages in src/main/java: com.example.schema for application classes and com.example.schema.model for entity classes. In IntelliJ, right-click src/main/java and select New > Package. In VS Code, right-click the java folder and create the directory path manually.

The project structure at this point:

Drop the Existing Schema

The Music Store schema currently exists as SQL-created tables from the previous tutorials. You recreate it from annotations, so the existing tables need to go first.

Create DropSchema.java in the com.example.schema package:

Run DropSchema from your IDE. In IntelliJ, click the green arrow in the gutter next to main(). In VS Code, click Run above the method signature. The output confirms each table and zone is removed:

Tables are dropped in reverse dependency order: leaves before parents, children before roots. The zones are dropped last, after all tables that reference them are gone. DROP TABLE cascades to indexes automatically, so the secondary indexes you saw in the previous tutorial are removed with their tables.

Prefer the CLI? Run these SQL statements instead.

The same DDL operations work from the CLI. The catalog API also provides dropTable() and dropZone(). SQL DDL does the same and works regardless of which tool you use.

Annotations are a creation-time mechanism. They generate DDL and execute it against the cluster. After createTable() runs, the distributed catalog owns the schema. The annotations themselves are not stored in the cluster or re-evaluated at runtime. The next step recreates the same schema from a different source (Java classes instead of DDL files), and both paths produce the same catalog entries.

Define Single-Key Entities

Start with two single-key entities: Artist (catalog root) and Genre (reference data). Together they introduce the four core annotations and demonstrate zone selection as an annotation-level decision.

Create Artist.java in the com.example.schema.model package:

Four annotations define the entire table:

Annotation
What it expresses
DDL equivalent

@Table

Maps this class to a distributed table named "Artist"

CREATE TABLE Artist (...)

@Zone

Assigns to MusicStore zone with 25 partitions, 2 replicas

CREATE ZONE IF NOT EXISTS MusicStore WITH ... + ZONE MusicStore

@Id

Marks ArtistId as the primary key

PRIMARY KEY (ArtistId)

@Column

Maps each field to a column with type, nullability, and length constraints

ArtistId INT NOT NULL, Name VARCHAR(120) NOT NULL

The @Zone annotation on @Table does double duty. When createTable() runs, it generates a CREATE ZONE IF NOT EXISTS statement before the CREATE TABLE. Zone creation is automatic. You do not need to create zones separately the way you did with SQL DDL in the previous tutorial.

Genre is a reference table: 25 rows, rarely updated, joined by queries from both the catalog and commerce tables. In the previous tutorial, you placed it in the MusicStoreReplicated zone (3 replicas on a 3-node cluster, so every node has a full copy). The annotation expresses the same decision.

Create Genre.java:

The only structural difference from Artist is the zone: MusicStoreReplicated with replicas = 3. The catalog API generates a separate CREATE ZONE IF NOT EXISTS MusicStoreReplicated statement with its own configuration. Two Java classes, two zones, each with the replication strategy that matches its workload.

Here is how each annotation maps to the DDL that createTable() generates and executes. The left column is what you wrote in the Java class; the right column is the equivalent SQL clause from the previous tutorial:

Java annotation
Generated DDL

@Zone(value = "MusicStore", partitions = 25, replicas = 2)

CREATE ZONE IF NOT EXISTS MusicStore WITH PARTITIONS=25, REPLICAS=2, STORAGE_PROFILES='default'

@Table on Artist

CREATE TABLE IF NOT EXISTS PUBLIC.ARTIST (...) ZONE MUSICSTORE

@Id + @Column(value = "ArtistId", nullable = false)

ARTISTID INT32 NOT NULL, PRIMARY KEY (ARTISTID)

@Column(value = "Name", nullable = false, length = 120)

NAME STRING NOT NULL with length 120

@Zone(value = "MusicStoreReplicated", replicas = 3)

CREATE ZONE IF NOT EXISTS MusicStoreReplicated WITH REPLICAS=3, ...

@Table on Genre

CREATE TABLE IF NOT EXISTS PUBLIC.GENRE (...) ZONE MUSICSTOREREPLICATED

Every clause is one you wrote by hand in the previous tutorial. The annotations express the same decisions as Java declarations instead of SQL statements.

Verify that the annotations produce the right tables by creating them on the cluster. Create CreateCatalogEntities.java in the com.example.schema package:

Run CreateCatalogEntities, then verify the zones from the CLI:

Two createTable() calls produced two zones and two tables. The @Zone annotation on each class triggered CREATE ZONE IF NOT EXISTS automatically.

Express Colocation as Code

Artist and Genre are independent entities with single-field primary keys. The catalog tables (Album and Track) introduce composite keys, colocation declarations, and secondary indexes. These three concepts were separate DDL clauses in the previous tutorial.

The catalog tables declare colocation columns, but each table's partition is decided only by hashing its own colocation column. Colocation does not chain through a middle table. Two different things happen here:

  • Colocated pair (Artist and Album): Album declares colocateBy: ArtistId, the same column that is Artist's key. An Artist row and every Album row with the same ArtistId hash to the same partition, so Artist JOIN Album is local.

  • Grouped only (Track): Track declares colocateBy: AlbumId. All tracks of one album share a partition with each other, but a Track row is not placed with its Album row (Album is hashed by ArtistId) or with its Artist row. Joining Track to Album or Artist moves data. To place Track with Artist, Track would need its own ArtistId column to colocate by, which this schema does not have.

In the diagram, a solid arrow is a colocated pair and a dashed arrow only groups the child rows by that column.

The italicized column in each PK is the colocation column. Artist (green) is the root. Album (teal) is colocated with Artist. Track (purple) is only grouped by album. You are about to express these relationships as @Id fields and colocateBy annotations.

Create Album.java:

Album introduces three concepts that were separate DDL clauses in the previous tutorial. Here they converge on a single class because you already understand the design reasoning. The annotation-to-DDL table shows how each maps:

Annotation
What it expresses
DDL equivalent

Two @Id fields

Composite primary key

PRIMARY KEY (AlbumId, ArtistId)

colocateBy = @ColumnRef("ArtistId")

Partition routing by ArtistId

COLOCATE BY (ArtistId)

indexes = @Index(...)

Secondary index for join support

CREATE INDEX IF NOT EXISTS IFK_AlbumArtistId ON Album (ArtistId)

The @ColumnRef annotation serves two roles on the same class:

  • In colocateBy it names the column whose hash decides which partition holds the row. For Album that is the same column Artist uses, so the two tables form a colocated pair.

  • In indexes it names the columns that make up a secondary index.

The annotation-to-DDL mapping for Album shows all three new concepts:

Java annotation
Generated DDL

@Id on AlbumId + @Id on ArtistId

PRIMARY KEY (ALBUMID, ARTISTID)

colocateBy = @ColumnRef("ArtistId")

COLOCATE BY (ARTISTID)

indexes = @Index(value = "IFK_AlbumArtistId", columns = @ColumnRef("ArtistId"))

CREATE INDEX IF NOT EXISTS IFK_ALBUMARTISTID ON PUBLIC.ALBUM (ARTISTID ASC)

Compare these with the DDL you wrote in the previous tutorial. The composite PK, COLOCATE BY, zone assignment, and secondary index are the same clauses. You can verify what the annotations actually created by querying the system views from the CLI after running CreateSchema in a later step.

Complete the catalog tables with Track. Create Track.java:

Track demonstrates three things beyond what Album covered:

  • Multiple indexes in an array: indexes = { @Index(...), @Index(...), @Index(...) }. Each serves a different query pattern.

  • BigDecimal with precision and scale: @Column(precision = 10, scale = 2) generates DECIMAL(10,2) for monetary values.

  • Nullable vs non-nullable fields: GenreId, Composer, and Bytes are nullable (default). TrackId, AlbumId, Name, MediaTypeId, Milliseconds, and UnitPrice are explicitly nullable = false.

The two classes declare colocation differently: Album is colocated with Artist by ArtistId (a colocated pair), and Track is grouped by AlbumId (all tracks of one album share a partition, but not with the Album row). In the previous tutorial, you saw these declarations as DDL clauses. Here they are expressed as @Id fields and colocateBy annotations across two Java classes.

Create both tables on the cluster to verify the colocation annotations. Add Album and Track to your creation class, or create a new one:

Then verify the composite PKs and colocation columns from the CLI:

The same PK and colocation ordinals from the previous tutorial. ARTISTID is PK ordinal 1 and colocation ordinal 0 on Album. ALBUMID is PK ordinal 1 and colocation ordinal 0 on Track. The @Id field order in the Java class determined the PK column order, and colocateBy set the colocation assignment.

Verify the indexes:

Four SORTED indexes, one per @Index annotation. Album has one index for the colocation join. Track has three: one for the Track-Album join (AlbumId), two for cross-references to the replicated zone tables (GenreId, MediaTypeId).

Define the Commerce Tables

The commerce tables follow the same structure as the catalog tables, with a different root entity and different colocation columns. Customer and Invoice form a colocated pair by CustomerId. InvoiceLine is grouped by InvoiceId: all lines of one invoice share a partition, but a line is not placed with its Invoice row (hashed by CustomerId) or its Customer row.

Customer (green) is the root. Invoice (orange) is colocated with Customer. InvoiceLine (purple) is only grouped by invoice. The same annotation patterns apply: composite @Id for the colocation column, colocateBy for partition routing, @Index for join support.

Create Customer.java:

Customer has more fields than Artist, but the annotation structure is the same:

  • Single @Id for the primary key (CustomerId is both PK and colocation column)

  • Required fields like FirstName, LastName, and Email use nullable = false

  • Optional fields like Company, Address, and Phone use the @Column default of nullable = true

Create Invoice.java:

Invoice introduces two type mappings beyond Integer and String:

  • LocalDate maps to SQL DATE for InvoiceDate. The type mapping matters: using String instead of LocalDate generates VARCHAR, and loading data with DATE values would fail with a type mismatch.

  • BigDecimal with precision and scale for Total, the same pattern as Track's UnitPrice.

Create InvoiceLine.java:

InvoiceLine has two indexes that serve different purposes:

Index
Purpose
What it helps
What it does not change

IFK_InvoiceLineInvoiceId

Invoice join support

Scans within each partition for InvoiceId matches. InvoiceLine is not placed with its Invoice row, so the join still moves data.

Colocation. Invoice is hashed by CustomerId.

IFK_InvoiceLineTrackId

Track join support

Scans within each partition for TrackId matches

Colocation. Track lives on a different partition.

An index speeds up the scan within each partition. It does not move data between partitions. The IFK_InvoiceLineTrackId index makes the scan faster on every node, and the join to Track from the previous tutorial still requires Exchange operators to shuffle data between nodes because Track and InvoiceLine are on different partitions. Indexes and colocation solve different problems.

The full Music Store schema has two colocated pairs with grouped-only tables, two reference tables, and references that cross colocation boundaries:

Solid arrows are colocated pairs (rows with the same key value on the same partition). Dashed arrows between a table and its grouped child (Album to Track, Invoice to InvoiceLine) only group the child rows by that column; the child is not placed with the parent row. Other dashed arrows are references across colocation boundaries (data on different partitions, joins require network). The reference tables (pink) are replicated to every node, so their dashed arrows never cause data movement. The InvoiceLine-to-Track dashed arrow is the join across colocation boundaries that the previous tutorial showed requiring Exchange operators.

Music Store schema reference: all tables, zones, colocation, and indexes
Color
Role
Examples

Green

Root (single PK, colocation anchor)

Artist, Customer, Playlist

Teal

Album is colocated with Artist (a colocated pair).

Album

Orange

Invoice is colocated with Customer (a colocated pair).

Invoice

Purple

Grouped only: rows are grouped by their own column and are not placed with the parent row.

Track (by AlbumId), InvoiceLine (by InvoiceId)

Yellow

Playlist child (colocated with Playlist)

PlaylistTrack

Pink

Replicated reference data (every node has a copy)

Genre, MediaType

Gray

Independent entity (not colocated with any other table)

Employee

Arrow
Meaning

Solid

Colocated pair: rows with the same key value share a partition. Joins are local.

Dashed

Grouping-only or cross-boundary reference: rows are on different partitions than the referenced rows. Joins move data, except joins to the replicated Genre and MediaType tables, which are local on every node.

What Annotations Cannot Express

Not every SQL feature has an annotation equivalent. The gaps are in standard SQL constraints, not in the distributed-specific features:

Feature
SQL DDL
Annotations
Workaround

Table structure (columns, types, PKs)

Yes

Yes

-

Composite primary keys

Yes

Yes

-

Colocation (COLOCATE BY)

Yes

Yes

-

Distribution zones (full config)

Yes

Yes

-

Secondary indexes

Yes

Yes

-

Default values

Yes

No

columnDefinition escape hatch

Annotations cover the distributed-specific decisions: zones, colocation, composite keys, indexes. GridGain 9.1 SQL has no foreign key, CHECK, or UNIQUE constraints and no generated columns, so there is nothing to supplement for those. Default values go through the columnDefinition escape hatch.

IgniteCatalog also accepts TableDefinition builders for teams that prefer programmatic schema construction or need to generate schemas dynamically. Annotations and builders are two input paths into the same catalog system.

Create the Schema From Annotations

You have seven entity classes covering the catalog tables, the commerce tables, and the reference data zone. The Music Store has four more tables that apply the same patterns: a second reference table, an independent entity with a self-referencing hierarchy, and the playlist tables from the previous tutorial's exercise.

Create MediaType.java in the com.example.schema.model package. MediaType is the second reference table, using the same replicated zone as Genre:

Employee is the only Music Store entity that is not colocated with any other table. It has a single PK and a self-referencing hierarchy through ReportsTo. Create Employee.java:

Playlist and PlaylistTrack form a third colocated pair, the one you analyzed in the previous tutorial's exercise. Playlist is the root entity. Create Playlist.java:

PlaylistTrack is a junction table with a composite PK and colocation by PlaylistId, the same pattern as Album (composite PK, colocateBy) but for a many-to-many relationship. Create PlaylistTrack.java:

All 11 entity classes are in place. Create CreateSchema.java in the com.example.schema package to build the schema from annotations:

Run CreateSchema. The output shows each table created and verifies the schema against the system views:

Verify independently from the CLI using the same queries from the previous tutorial:

This is the same query and the same output from the previous tutorial. The zone assignments and colocation columns are identical regardless of whether the tables were created via SQL DDL or Java annotations.

Both zones match the @Zone annotations: MusicStore with 2 replicas and MusicStoreReplicated with 3 replicas. The Default zone (pre-created by the cluster) is unused because every entity class specifies a zone explicitly.

Now look at the return type of each createTable() call. It returns a Table object, the same object you get from client.tables().table("Artist"). That means Artist.java is not just a schema definition you throw away after table creation. It is also the POJO you pass to table.recordView(Artist.class) for typed data access. One class carries two responsibilities: schema definition (zones, colocation, indexes) and runtime data mapping.

This has three practical consequences:

  • Type-safe operations. recordView(Artist.class) returns Artist objects, not Tuple. The compiler catches field name and type mismatches at compile time. With Tuple-based access, a typo in tuple.stringValue("Nme") is a runtime error.

  • @Id defines the key/value split. The @Id fields you declared on each entity determine the key portion for KeyValueView. Album's composite PK (AlbumId, ArtistId) means KeyValueView needs both fields for a point lookup. The annotations drive the API contract.

  • Refactoring safety. Rename a field in the POJO and the compiler finds every reference across the application. With column names in strings, renaming means searching for string literals and hoping you found them all.

Try this in your IDE: open Album.java and look at the @Table annotation. Without reading any DDL or querying any system view, you can see that Album colocates by ArtistId, lives in the MusicStore zone, and has a secondary index on ArtistId. Now use Find Usages (or Search for Symbol) on the string "ArtistId" across the model package. You find it in Artist.java as the @Id field (the colocation root) and in Album.java in both colocateBy and indexes. Track does not reference ArtistId at all because it colocates by AlbumId instead. The Artist-Album colocated pair, and the separate AlbumId grouping for Track, are navigable through your IDE's search without opening a DDL file.

When someone changes a colocation column or adds an index in a pull request, the change appears alongside the application code that depends on it.

The next tutorial, Choose the Right Data Access Pattern, uses these same entity classes with RecordView, KeyValueView, and SQL to show how composite primary keys and colocation columns determine which API view works for each operation.

The annotations defined the schema, and the catalog now owns it. If a DBA alters a table via SQL (adds a column, changes a type), the annotations become stale, but SYSTEM views and the Table API still reflect reality.

Treat annotations as a deployment artifact and the catalog as the runtime source of truth. This is why the verification step matters: system views confirm what the catalog actually contains, regardless of how the tables were created.

Note that createTable() generates CREATE TABLE IF NOT EXISTS, so running CreateSchema against a cluster that already has these tables does nothing for them. It does not alter an existing table that differs from the annotations. Run DropSchema first if you need to recreate the schema.

Reload and Verify

The annotation-created tables are structurally identical to the SQL-created ones, so the same data files work without modification. Download the data file and load it:

The data loader prints row counts per batch. When it finishes, verify the partition distribution:

Partition counts per node and row estimates vary by cluster. The pattern is consistent: MusicStore partitions are distributed across nodes, MusicStoreReplicated partitions are on every node.

The partition distribution matches what you saw in the previous tutorial. MusicStore partitions are spread across nodes, and MusicStoreReplicated shows every partition on every node (3 replicas, 3 nodes). The same data files loaded without modification. The same partition distribution resulted. The annotation-created schema is structurally identical to the SQL-created one.

Run a colocated commerce query to confirm the data is queryable:

The colocated Customer-Invoice join executes on a single partition, the same behavior you verified in the previous tutorial with the SQL-created schema.

Summary

The Music Store schema is now defined in 11 Java classes instead of DDL files. The annotation-created schema is structurally identical to the SQL-created one from the previous tutorial: same zones, same colocation columns, same partition distribution, same query behavior.

The classes deliver two things at once. As schema definitions, they make distributed design decisions visible in your IDE, reviewable in pull requests, and versioned in git. A schema change is a code change that goes through the same review process as application logic. As runtime POJOs, they provide type-safe data access through RecordView and KeyValueView, compile-time field checking instead of string-based column names, and refactoring safety when column names change.

Six annotations express all distributed schema design decisions:

  • @Table maps a class to a distributed table and bundles zone, colocation, and index declarations

  • @Zone configures distribution: partitions, replicas, storage profile. Zone creation is automatic.

  • @Id marks primary key fields. Colocation columns must be @Id. These fields also define the key portion for KeyValueView.

  • @Column maps fields to columns with type, nullability, and length constraints

  • @ColumnRef references columns for colocation (colocateBy) and indexes

  • @Index declares secondary indexes for join and query support

The catalog API generates the same DDL you wrote by hand in the previous tutorial: CREATE ZONE, CREATE TABLE, CREATE INDEX. After creation, the catalog owns the schema. Default values, which annotations cannot express directly, can be set with the columnDefinition escape hatch.

Both paths produce identical schemas. The choice depends on your team's workflow. Annotations are the stronger choice when your team works in Java and uses RecordView or KeyValueView for data access, because the same class defines the schema and maps the data. DDL is the stronger choice for multi-language teams, DBA-managed schemas, or workflows that rely on migration tools like Flyway or Liquibase. Many teams use both: annotations for application-managed tables, DDL for shared infrastructure tables.

What's next:

The entity classes you built are not finished artifacts. They are the data access layer for every operation your application performs. Choose the Right Data Access Pattern passes these same classes to RecordView, KeyValueView, and SQL, and shows how the composite primary keys and colocation columns you declared determine which API view works for each operation. Album's composite PK (AlbumId, ArtistId) means KeyValueView needs both fields for a point lookup, but SQL can query by ArtistId alone. The schema design decisions from the previous tutorial, now embedded in your Java code, shape the application you build on top of them.

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

Last updated

Was this helpful?