apache avatar

apache-cayenne-5

Apache Cayenne 5.0 ORM — the same skills for projects on the 5.0 release line.

GitHub stars
348

Install

/plugin install apache-cayenne-5@apache-cayenne

Run it inside Claude Code after adding the marketplace with /plugin marketplace add apache/cayenne.

Contents

Discovered from source

Skills 8

cayenne-cgen

Run Cayenne's class generator on a DataMap via the mcp__cayenne__cgen_run MCP tool. The tool reads the embedded <cgen> block in the DataMap to determine destination, mode, templates, etc.; if no block is present the tool generates anyway using a sensible default config (all entities, makePairs=true, destination derived from the Maven layout). A missing <cgen> block is not an error and must never stop you from running the tool.

Required reading

  • ${CLAUDE_PLUGIN_ROOT}/references/mcp-tools.md — cgen_run tool reference (arguments, return shape, failure modes).
  • ${CLAUDE_PLUGIN_ROOT}/references/cgen-config.md — every <cgen> field; needed when the user has to add or tweak the config block.
  • ${CLAUDE_PLUGIN_ROOT}/references/project-layout.md — locate the project descriptor.

Step 1 — Resolve project and DataMap

The MCP tool needs two arguments:

  • projectPath — absolute path to the top-level project descriptor (cayenne-*.xml). Not a DataMap file.
  • dataMap — the name as it appears in <map name="..."> in the descriptor. Not a file path.

Locate the descriptor via project-layout.md. If multiple descriptors exist, ask which one. Open the descriptor to extract the DataMap names from <map> elements.

If the user named the DataMap directly (e.g. "regenerate classes for the customers DataMap"), use that. If they said "regenerate everything" and there are multiple DataMaps, run cgen_run once per DataMap in sequence (the tool generates per-DataMap).

Step 2 — Call cgen_run

mcp__cayenne__cgen_run({
  "projectPath": "<absolute path to cayenne-*.xml>",
  "dataMap": "<map name from the descriptor>"
})

Call the tool directly for each DataMap — never inspect the DataMap for a <cgen> block first, and never treat its absence as a blocker. The tool generates with a default config when no block exists.

If the tool is not available (MCP server not registered), surface cayenne-mcp-server/README.md and stop. Do not suggest mvn cayenne:cgen or the Gradle cgen task.

Step 3 — Surface the result

The tool returns structured JSON. Report:

  • summary.filesConsidered and summary.filesWritten verbatim — these are the headline.
  • The first few entries in files (relative paths). Full list is informational; offer to dump it if the user asks.
  • error, when non-null — this is blocking. Read the message and explain in user terms (a missing entity class name, a bad template path, an invalid <destDir>, etc.).
  • resolved.destDir — the absolute output directory. If the DataMap had no <cgen> block, the tool generated from a synthesized default; report this destination so the user can confirm it's right, and offer to persist a <cgen> block (via cayenne-modeling) if they want to customize destination, templates, or entity filtering.

cgen always runs in full, but rewrites a file only when the generated contents differ from what is on disk. So files is exactly what changed, and a status of up_to_date means the Java was already in sync with the model — say so plainly rather than implying work was skipped.

Step 4 — Next steps

  • If new _<Entity>.java superclass files were generated, gently remind the user not to edit those — they will be overwritten next run. User code goes in the matching <Entity>.java subclass.
  • If the user just ran reverse engineering, this skill is the natural follow-up. Cross-link back to cayenne-modeling if they need to tweak names/types before regenerating.

Anti-patterns

  • Do not pre-check the DataMap for a <cgen> block before calling cgen_run, and do not add a block before running. A missing block is not an error — the tool generates with defaults. Only add a <cgen> block afterward if the user wants to persist or customize the config.
  • Do not suggest Maven (mvn cayenne:cgen) or Gradle (cayenneCgen) goals when MCP is unavailable. Those build plugins are out of scope. Point at MCP setup instead.
  • Do not edit _<Entity>.java files. Generated superclasses. Edit <Entity>.java subclasses.
  • Do not confuse projectPath and dataMap arguments. projectPath is a file system path to cayenne-*.xml. dataMap is a logical name (e.g. mydb), not a path to mydb.map.xml.

cayenne-db-import

Import a database schema into a Cayenne DataMap using the mcp__cayenne__dbimport_run MCP tool. If a DBConnector is already stored in preferences for the DataMap the import runs directly without any GUI interaction. When the connection has not been configured yet, the workflow launches CayenneModeler and walks the user through the dialog once to save the connection, then re-runs dbimport_run.

Required reading

  • ${CLAUDE_PLUGIN_ROOT}/references/project-layout.md — locate or create the project descriptor.
  • ${CLAUDE_PLUGIN_ROOT}/references/dbimport-config.md — field semantics for every dialog screen, so you can explain options in user terms.
  • ${CLAUDE_PLUGIN_ROOT}/references/mcp-tools.md — dbimport_run and open_project tool references and failure modes.

Ownership

DB import owns the DB layer of the DataMap: <dbEntity>, <dbAttribute> and <dbRelationship> elements are derived from DB metadata, never typed by hand. This applies to a one-column change as much as to a full schema import — the DB schema is changed first, then the import brings it into the model. The Object layer, queries and config blocks are hand-edited via cayenne-modeling.

The one exception is a user who has explicitly said they do not use DB import for the project. Then cayenne-modeling hand-edits the DB layer and this skill is not used. Never assume that exception yourself: a <dbImport> block in the DataMap means DB import is in use; without one, and without an earlier answer from the user, cayenne-modeling asks once and saves the answer to persistent memory.

After a successful import into a DataMap whose status was unclear, save to persistent memory (if you have one) that the project uses DB import.

dbimport_run is a merge that applies every difference without prompting:

  • DB-layer elements that match the DB are kept; new tables, columns and FKs are added.
  • DB-layer elements with no counterpart in the DB — within the <dbImport> filters — are removed, including tables and relationships somebody added by hand. If the user mentions such elements, warn them before running, and suggest excluding them in <dbImport> or creating them in the DB first.
  • Object-layer edits (names, Java types, extra attributes) on entities that still match the DB are kept.
  • Relationships are the one part governed by a setting. With <skipRelationshipsLoading>true</skipRelationshipsLoading> in <dbImport>, the import neither reads FKs nor removes relationships from the model — DbRelationships are then the user's, hand-edited via cayenne-modeling. With false (the default), every FK is imported and a hand-made relationship with no FK in the DB is removed. Don't change this setting unless the user asks.

Step 1 — Confirm scope

Ask the user (one question, only if not obvious from the request):

  • Are they reverse-engineering into a new DataMap, or adding/updating entities in an existing DataMap?

Step 2 — Locate or create the project

Follow project-layout.md to find the existing cayenne-*.xml. If none exists, the user is starting from scratch:

  • Either generate a minimal descriptor first (use cayenne-modeling's patterns — namespace http://cayenne.apache.org/schema/12/domain, project-version="12", one empty <map name="..."/> plus a sibling empty *.map.xml), or
  • Tell the user to use File → New Project inside the Modeler once it's open.

The descriptor path needs to be absolute when passed to the MCP tools.

Step 3 — Run dbimport_run

Call the MCP tool:

mcp__cayenne__dbimport_run({ "projectPath": "<absolute path to cayenne-*.xml>", "dataMap": "<DataMap name>" })

If the tool is not available (server not registered), surface cayenne-mcp-server/README.md and stop. Do not suggest mvn cayenne:cdbimport or any Gradle equivalent — those build plugins are out of scope.

Interpreting the result

  • imported — success. Surface the summary counters (entities added/removed/modified, relationships added) to the user. Call out a non-zero entitiesRemoved explicitly — those entities were dropped from the model without a prompt.
  • up_to_date — the DataMap already matches the database. Tell the user nothing changed.
  • error — import started but failed mid-run. Show the error.message and the partial summary.
  • validation_failed — a pre-flight check failed. Use the error.code to guide next steps (see below).

Validation failures and their remediation

CodeWhat failedWhat to do
project_not_foundProject path not readableVerify path.
project_parse_failedFile is not a valid Cayenne descriptorConfirm the file is a cayenne-*.xml.
datamap_not_foundDataMap name not in projectThe error message lists available names; use one.
dbconnector_not_configuredNo connection saved for this DataMap→ Go to Step 4 to configure via the Modeler dialog.
jdbc_driver_not_loadableDriver jar not on the Modeler classpathOpen CayenneModeler → Preferences → Classpath, add the driver jar, save, then re-run.
jdbc_connection_failedConnection could not be openedCheck JDBC URL, credentials, and network access.

Step 4 — Configure the connection (first-time only)

This step is only needed when dbimport_run returns dbconnector_not_configured.

4a — Launch the Modeler

mcp__cayenne__open_project({ "projectPath": "<absolute path to cayenne-*.xml>" })

If open_project returns a non-ok status, surface the error code; common ones are modeler_not_found, project_not_found, handshake_timeout. Don't retry blindly — diagnose first.

4b — Walk the user through the dialog

The user now has the Modeler open. Give them the exact GUI sequence:

  1. DataMap → DB Import tab
  2. Data Source dialog:
    • JDBC Driver — e.g., org.postgresql.Driver
    • DB URL — full JDBC URL
    • User Name / Password — credentials
    • Cayenne Adapter (optional, autodetected for known DBs)
    • Click Test Connection, then Continue.
  3. Configure screen — set table/column/procedure filters:
    • Include/exclude regex patterns under the relevant catalog/schema.
    • Table Types — usually TABLE; add VIEW if needed.
  4. Naming screen:
    • Naming Strategy, Strip from Table Names, Default Package, Meaningful PK Tables.
    • See dbimport-config.md for what each does.
  5. Other Options — toggles for skipPrimaryKeyLoading, skipRelationshipsLoading, etc.
  6. Click Save (not Run Import — the goal here is to save the connection, not run the import through the GUI).

After the user saves, the DBConnector is written to CayenneModeler preferences.

4c — Re-run dbimport_run

Go back to Step 3 and call dbimport_run again. This time it should find the saved connection and proceed.

Step 5 — Confirm and follow up

Once the import succeeds:

  • Tell the user to save the project in the Modeler if it is open (File → Save). The dialog settings persist as a <dbImport> block inside the DataMap for repeat runs.
  • Hand off to cayenne-cgen to regenerate Java classes for the new/changed entities. Quote the DataMap name so the cgen skill can pass it to cgen_run.
  • If the imported names look awkward (run-together words, team1-style relationship names, a table prefix leaking into relationships), you can offer the cayenne-model-naming skill to polish them — ideally before cgen. Only run it if the user asks; do not invoke it automatically.
  • If the DB has columns that don't follow the user's preferred naming, recommend tweaking the naming strategy and re-running.

Anti-patterns

  • Do not suggest mvn cayenne:cdbimport, the Gradle cdbimport task, or hand-running the cayenne-dbsync Java APIs. dbimport_run is the only supported execution path.
  • Do not hand-write any part of the DB layer as a substitute for an import — not a whole DataMap from a schema description, and not a single <dbEntity>, <dbAttribute> or <dbRelationship> "because it's just one". The import handles JDBC types, PK detection, FK relationships, and naming consistently; hand-rolling produces subtle mistakes and is overwritten by the next import. The only exception is a user who explicitly does not use DB import (see "Ownership").
  • Do not enable forceDataMapCatalog / forceDataMapSchema defensively. They suppress legitimate DB metadata and cause hard-to-debug issues in multi-catalog setups.
  • Do not offer reverse engineering without MCP — if the server isn't connected, point at cayenne-mcp-server/README.md and stop.
  • Do not run the import through the Modeler GUI dialog when dbimport_run is available — the GUI path is only for the first-time connection setup.

cayenne-full-db-sync

Bring an entire Cayenne project in line with the database in one pass. This skill is a thin orchestrator — it runs three existing skills in sequence and does not re-implement any of their logic:

  1. cayenne-db-import — import DB schema metadata into the DataMap (the mapping XML).
  2. cayenne-model-naming — polish the Object-layer names of what the import just added.
  3. cayenne-cgen — regenerate the Java entity classes so the code matches the model.

Each sub-skill still runs within its own scope and carries its own required reading, MCP tool usage, failure handling, and anti-patterns. Your job here is to drive them in order, pass the shared project/DataMap identity through, and short-circuit correctly when a stage has nothing to do.

When to use this vs. a single skill

  • Whole project should reflect the DB (mapping + names + Java) → this skill.
  • Model/mapping only, no name cleanup or class generation → cayenne-db-import.
  • Java classes only, model already correct → cayenne-cgen.
  • Names only, no import or regeneration → cayenne-model-naming.

If the request is ambiguous ("update from the DB"), default to this full sync — it is the common intent — but say what you're about to do (import → clean names → regenerate) before you start.

Required reading

This skill delegates, so read each sub-skill and let it pull its own references:

  • ${CLAUDE_PLUGIN_ROOT}/skills/cayenne-db-import/SKILL.md
  • ${CLAUDE_PLUGIN_ROOT}/skills/cayenne-model-naming/SKILL.md
  • ${CLAUDE_PLUGIN_ROOT}/skills/cayenne-cgen/SKILL.md
  • ${CLAUDE_PLUGIN_ROOT}/references/project-layout.md — to resolve the project descriptor and DataMap once, up front.

Step 0 — Resolve the shared inputs once

All three stages operate on the same project. Resolve these before starting so you can pass them through:

  • projectPath — absolute path to the top-level project descriptor (cayenne-*.xml), via project-layout.md. Not a DataMap file.
  • dataMap — the DataMap name from <map name="..."> in the descriptor. If the project has multiple DataMaps and the user wants "everything", run the whole pipeline once per DataMap. If ambiguous, ask which DataMap; cache the answer.

Tell the user the plan in one line: "I'll import from the DB, clean up the new names, then regenerate the classes."

Step 1 — Import (cayenne-db-import)

Follow the cayenne-db-import skill to run dbimport_run for the resolved project/DataMap. Because you are orchestrating, you drive the follow-up here — do not act on that skill's own Step 5 hand-off prompts (it would suggest naming/cgen again); this skill sequences them instead.

Branch on the result status:

  • imported with a non-empty summary (entities/relationships added/modified) → the model changed. Proceed to Step 2.
  • up_to_date (or imported with an all-zero summary) → the mapping already matches the DB. Skip Step 2 (nothing new to name). Go straight to Step 3 to guarantee the Java classes are in sync — cgen_run is idempotent and simply reports everything skipped if the code is already current. Tell the user the model was already up to date.
  • validation_failed → follow cayenne-db-import's remediation table for the error.code. The common first-run case is dbconnector_not_configured, which routes through the Modeler GUI to save the connection; once resolved, re-run the import and continue the pipeline. If it can't be resolved, stop and surface the problem — do not run naming or cgen on a failed import.
  • error (partial/mid-run failure) → surface error.message and the partial summary, then stop. Don't proceed to naming or cgen.

Step 2 — Clean up names (cayenne-model-naming)

Only when Step 1 imported real changes. Follow the cayenne-model-naming skill in its changed-only mode — it scopes itself to the import's additions via git diff, so you don't tell it which entities changed. Within this pipeline it runs unattended: apply the changed-scope renames and report what changed; do not pause for per-rename confirmation. (Naming must run before cgen so the classes are generated with the final names.)

Two carry-overs from that skill still hold: it only touches what the deterministic generator can't get right (run-together names, team1-style collisions, a table prefix leaking into relationships), and every rename updates its cross-references per model-naming-rename-safety.md.

Step 3 — Regenerate classes (cayenne-cgen)

Follow the cayenne-cgen skill to run cgen_run for the same project/DataMap. This materializes the Java entity classes from the now-final model. Report the summary counts and the destination as that skill describes.

Step 4 — Summarize the whole run

Give the user a single consolidated report of the three stages:

  • Import — entities/relationships added/removed/modified (from the dbimport_run summary).
  • Names — the renames applied (old → new), or "none needed".
  • Classes — files written / skipped, and the destination directory.

Then the usual follow-ups: remind them not to edit the _<Entity>.java superclasses (regenerated), and to save the project in the Modeler if it's open.

Anti-patterns

  • Don't use this for a single stage. Model-only import → cayenne-db-import; classes-only → cayenne-cgen; names-only → cayenne-model-naming. This skill is for the whole pipeline.
  • Don't re-implement the sub-steps. Delegate to each skill so its MCP tool usage, failure modes, and anti-patterns all apply. This file only sequences and short-circuits.
  • Don't run naming or cgen after a failed or empty import. A validation_failed/error stops the pipeline; up_to_date skips naming (but cgen may still run as an idempotent guarantee).
  • Don't reorder the stages. Names must be finalized before cgen, or classes are generated with the names you're about to change.
  • Don't rewrite the whole model during a sync. Naming stays in changed-only scope (import additions), never an entire-model pass, unless the user explicitly asks for one.
  • Don't suggest mvn cayenne:cdbimport / cayenne:cgen or the Gradle tasks. The sub-skills use the MCP tools exclusively; if the server isn't connected, they point at cayenne-mcp-server/README.md and stop.

cayenne-model-naming

Polish the Object-layer names in a Cayenne DataMap so they look like idiomatic Java. This runs on top of the names CayenneModeler's reverse engineering already produced — which are good for the common case. Your job is a surgical touch-up of the few names its deterministic algorithm can't get right, not a rewrite. If a name is already a clean camelCase/PascalCase transliteration of its DB element with the right cardinality, leave it exactly as it is.

Required reading

  • ${CLAUDE_PLUGIN_ROOT}/references/model-naming-conventions.md — the deterministic baseline (what's already correct and must be left alone) and the specific gaps where your judgment adds value.
  • ${CLAUDE_PLUGIN_ROOT}/references/model-naming-rename-safety.md — the cross-reference checklist for every rename, so a rename never leaves a dangling reference.
  • ${CLAUDE_PLUGIN_ROOT}/references/datamap-schema.md — element shapes for *.map.xml.
  • ${CLAUDE_PLUGIN_ROOT}/references/project-layout.md — locate the project descriptor and DataMap.

Step 1 — Determine scope: changed elements vs the entire model

There are two modes, and picking the right one is the most important decision in this skill:

  • Changed-only (the default, e.g. when the user runs this after a cayenne-db-import) — only inspect the names on newly-added or just-modified elements. Everything else in the model was presumably reviewed already; don't churn it.
  • Entire model (rare) — inspect every Obj element. Use this only when the user explicitly asks for it ("clean up the whole model", "normalize all the names", "go over every entity").

dbimport_run does not report which entities changed (it reports change counts though, so use it as an extra hint), so detect the changed set with git. Run these from the repo containing the DataMap file:

# Is the DataMap under version control at all?
git -C <repo-dir> rev-parse --is-inside-work-tree

# What did the import change (unstaged), and did anything get staged already?
git -C <repo-dir> diff -- <path/to/datamap>.map.xml
git -C <repo-dir> diff --cached -- <path/to/datamap>.map.xml

From the diff, collect the added/modified <objEntity>, <objAttribute>, <objRelationship>, and <dbRelationship> lines — that added/changed set is your scope. Notes:

  • If git diff is empty but the file is tracked, there's nothing new to clean — say so and stop (unless the user asked for an entire-model pass).
  • If the file is untracked / brand-new (no prior version in HEAD), every element is effectively "new" — treat it as an entire-model pass, but tell the user that's why.
  • Fallback: if it's not a git repository, or git isn't available, you can't scope by diff — fall back to the entire model and tell the user you couldn't narrow it down.

Step 2 — Find the names worth changing (and only those)

For each in-scope element, compare against model-naming-conventions.md. Most names will already be correct — leave them. Flag only the cases the deterministic generator can't handle:

  1. Run-together names with no separators — gametype → GameType, dateofbirth → dateOfBirth. Split on a real word boundary you're confident about; never invent one.
  2. Numbered collision names (projects / projects1, people / people1) from more than one relationship between the same two tables. The generator resolves the common cases itself: to-one names are FK-based even without an _ID suffix (HOME_TEAM_ID → homeTeam, BIRTH_COUNTRY → birthCountry), and to-many names pick up a FK role qualifier when the FK embeds the source entity name, even one sans a common table prefix (HOME_TEAM_ID → homeGames; home_team_id referencing aa_team → homeGames too). What still collides: to-many collections whose FK role is unrelated to the entity name (MANAGER_ID / AUDITOR_ID → projects / projects1 — rename by role: managedProjects / auditedProjects), and — in models imported by older Cayenne versions — to-one ends whose FK columns lack an _ID suffix and collapsed to employee / employee1.
  3. A common entity prefix leaking into relationship names — when every entity shares a prefix that was kept on the class names (AaCustomer, AaOrder), the prefix can leak into relationship names. The generator already keeps it out of to-many names (the leading _-tokens shared by the source and target table names are dropped → orders, not aaOrders); what leaks is to-one names built from prefixed FK columns (AA_CUSTOMER_ID → aaCustomer) and to-many names in models imported by older Cayenne versions (aaOrders). Strip the prefix from those relationship names (customer, orders); a relationship is a role/property, and the prefix is noise there. Leave the entity names alone — the prefix on classes is the user's choice, and renaming entities regenerates classes.
  4. Other clear, defensible improvements — illegal identifiers (digit-leading names; Java keywords are fine — cgen escapes them — and properties clashing with base-class getters like class / objectId are auto-qualified with the entity name by the generator, though older imports may carry them raw), lost acronym casing, obvious cryptic abbreviations applied consistently, plural-table-to-singular-entity. Conservative by default; when unsure, leave the baseline name and ask.

Relationship cleanup is anchored on the DbRelationship — it's the first-class citizen, since every FK has one whether or not an ObjRelationship was generated on top. The rules above (run-together, numbered collisions, prefix leak) apply to DbRelationship names directly, derived from their own DB metadata (FK column for to-one, pluralized target DbEntity for to-many). When an ObjRelationship is built on a DbRelationship, keep the two names in sync — rename both together, per direction. DbRelationships with no ObjRelationship (an ungenerated reverse direction, a skipped FK, a hop inside a flattened many-to-many) are cleaned the same way — don't skip them. Any rename must update every dbRelationshipPath segment that names it (see Step 4).

Step 3 — Present the rename plan

Show the user a table of old → new grouped by entity, plus the mirrored DbRelationship renames, and state plainly what you're leaving alone so it's clear this isn't a blanket rewrite.

  • Entire-model mode, or any rename of a name already referenced by user Java/queries → confirm before applying. Renaming an ObjEntity regenerates its class and can break existing code.
  • Changed-only, right after an import (new elements not referenced anywhere yet) → low risk; apply and report, but still list every rename you made.

If there are many domain abbreviations to expand, ask the user for a glossary rather than guessing.

Step 4 — Apply the renames safely

Edit the *.map.xml. For every rename, walk the matching checklist in model-naming-rename-safety.md and update all references in the same edit:

  • ObjEntity → className, every objRelationship source/target, query rootName, resultEntity.
  • ObjRelationship → prefetch/expression paths (its dbRelationshipPath is unaffected).
  • ObjAttribute → qualifier/ordering paths (its dbAttributePath is unaffected).
  • DbRelationship → every dbRelationshipPath segment that names it, including inside dotted flattened chains. This holds whether or not the DbRelationship backs an ObjRelationship — a standalone DbRelationship can still be named as a segment in another entity's flattened path.

Keep every name unique within its scope, and preserve the file's existing formatting and element order.

Step 5 — Validate and hand off

  • Re-walk the cross-reference checklist: does every source/target, rootName, dbRelationshipPath segment, and className still resolve?
  • Hand off to cayenne-cgen to (re)generate the Java classes with the final names. Naming must happen before cgen — if classes were already generated with the old names, point out the now-stale .java files so the user can regenerate/delete them.

Anti-patterns

  • Don't rewrite names the generator already got right. A camelCase attribute, a PascalCase entity, a plural to-many, an FK-derived to-one — all fine. This is polish, not a redo.
  • Don't clean the entire model when only an import changed things. Scope with git diff; default to changed-only.
  • Don't invent word splits. Split gametype → GameType only when the boundary is real; don't break single words (status, metadata).
  • Don't guess abbreviation expansions. Ask for a glossary when a model is full of them.
  • Don't rename an ObjEntity without updating className, every reference, and regenerating — a bare rename orphans the old class and dangles relationship source/target and query rootName.
  • Don't rename a DbRelationship without fixing every dbRelationshipPath segment, including flattened chains on other entities.
  • Don't skip a DbRelationship just because it has no ObjRelationship. Standalone DbRelationships are in scope — clean them on their own merits from their DB metadata, not by mirroring.
  • Don't repoint dbAttributePath / dbRelationshipPath targets. You rename the element; you never change what a path points to.
  • Don't run cgen yourself. Hand off to cayenne-cgen.

cayenne-modeler

Launch CayenneModeler with a Cayenne project file pre-loaded, via the mcp__cayenne__open_project MCP tool.

Required reading

  • ${CLAUDE_PLUGIN_ROOT}/references/mcp-tools.md — open_project tool reference and failure modes.
  • ${CLAUDE_PLUGIN_ROOT}/references/project-layout.md — locate the project descriptor.

Step 1 — Resolve the project path

The MCP tool needs an absolute path to a top-level project descriptor (cayenne-*.xml). Use project-layout.md to find it. If multiple descriptors exist, ask which one. Cache for the rest of the session.

If no descriptor exists yet, the user is starting from scratch. Two options:

  1. Create a minimal descriptor first (use cayenne-modeling to scaffold it), then open.
  2. Open the Modeler on any path it'll accept and use File → New Project inside.

For starting fresh, option 2 is simpler — but open_project does require an existing readable file.

Step 2 — Call open_project

mcp__cayenne__open_project({ "projectPath": "<absolute path to cayenne-*.xml>" })

If the tool is not available (MCP server not registered), surface cayenne-mcp-server/README.md and stop. Do not attempt to launch CayenneModeler by any other means — the bundled launcher relies on the MCP server's discovery of the Modeler installation.

The tool spawns the Modeler asynchronously, then waits up to ~15 seconds for a startup handshake. Possible return codes:

CodeMeaning
okModeler launched and loaded the project.
modeler_not_foundThe MCP jar is not co-located with a Modeler installation. User needs to install CayenneModeler properly.
project_not_foundThe projectPath doesn't exist or isn't readable.
handshake_timeoutThe Modeler started but didn't confirm load within the timeout. Often this means it's still loading — the user can check the GUI directly.
launch_failedProcess spawn failed. Surface the error message.

Step 3 — Hand off to the user

Once open_project returns ok, the user is in the GUI. From here, depending on intent:

  • Upgrading an older project: when the descriptor's project-version is lower than the current one, the Modeler offers to upgrade the project as it opens. Tell the user to accept the upgrade and save (File → Save), which rewrites cayenne-*.xml and every *.map.xml in the current format. Do not migrate the XML by hand, and hold any other model edits until the upgrade is saved.
  • Reverse engineering: that's the cayenne-db-import skill's job to walk them through. Do not duplicate that workflow here — just open and step out.
  • Visual layout / bulk editing: tell the user what tab to navigate to (e.g., DataMap → ObjEntity for entity-level edits, DataMap → Class Generation for cgen config) and let them work. Don't try to script GUI actions.
  • Just wanted to see the project: nothing more to do.

When NOT to use this skill

  • A-la-carte XML edits. Adding one ObjEntity, tweaking one ObjAttribute, renaming a relationship — all faster as direct XML edits via cayenne-modeling. Don't context-switch the user to the GUI for trivial work.
  • DB-layer changes. New or changed tables, columns and FKs come from cayenne-db-import (via dbimport_run), not from GUI editing — unless the user has explicitly said they do not use DB import.
  • Class generation. That's cayenne-cgen's job, fully scripted via MCP. No GUI needed.

Anti-patterns

  • Do not trigger as a generic fallback for "Cayenne tasks." This skill is for explicit user requests or inherently visual workflows. The cayenne-modeling skill handles most modeling intent.
  • Do not retry open_project on handshake_timeout — the Modeler may still be loading. Tell the user to check the GUI window directly.
  • Do not attempt to launch CayenneModeler outside the MCP tool (no java -jar direct calls, no opening a .dmg, no open -a CayenneModeler). The MCP tool's launcher knows where the installation lives.

cayenne-modeling

Edit Cayenne DataMap (*.map.xml) and project descriptor (cayenne-*.xml) files directly. This is the default path for granular model changes — adding one entity, one relationship, one query. Use the Modeler GUI (cayenne-modeler skill) only for inherently visual work like bulk relationship layout.

Who owns what — check this before any edit

A DataMap has two halves with different owners. The owner is decided by the layer being changed, not by the size of the change.

Part of the modelOwnerHow to change it
DB layer — <dbEntity>, <dbAttribute> (type, length, scale, mandatory, PK flags), <dbRelationship> and its joinsThe database, via DB importChange the DB schema, then run cayenne-db-import. Do not hand-edit. One settings-based carve-out for <dbRelationship> — see "DbRelationships follow the import settings".
Object layer — <objEntity>, <objAttribute>, <objRelationship>, inheritance, callbacksThe userHand-edit here.
Everything else — queries, <embeddable>, <procedure>, <cgen>, <dbImport> filters, the project descriptorThe userHand-edit here.

The only exception: hand-edit the DB layer when the user has explicitly said they do not use DB import for this project (e.g. "we don't reverse engineer", "the model is the source of truth and the schema is generated from it"). Then this skill owns both layers.

When a request needs a DB-layer change, settle whether the project uses DB import, in this order:

  1. The user already said — in the request, earlier in the session, in project instructions, or in your persistent memory for this project. Follow that.
  2. The target DataMap has a <dbImport> block — the project uses DB import. Don't ask.
  3. Otherwise it is unclear — ask once: "Do you use DB import (reverse engineering) to keep this DataMap in sync with the database, or do you maintain the DB layer by hand?" Then save the answer to your persistent memory for this project, if you have one (per DataMap, if the project has several and the answers differ), so the question is not repeated in later sessions. Without persistent memory, remember it for the rest of the session.
  • Do not infer the exception. A missing <dbImport> block is "unclear", not an opt-out — the block is optional and import works without one. The same goes for a missing DBConnector, an MCP server that isn't connected, or a table that doesn't exist in the DB yet.
  • If the project uses DB import, do not make the DB-layer change. Say the DB layer comes from DB import, and hand off to cayenne-db-import (after the user has applied the schema change to the DB, if it isn't there yet). This holds for a single table, column, nullability flag or FK just as for a bulk import.
  • If the user later says otherwise (they started or stopped using DB import), follow the new answer and update the saved memory.
  • Why: dbimport_run merges the DB into the model and applies every difference without prompting. Hand-written DB-layer elements that don't match the DB are overwritten or dropped on the next import, and hand-written types, PK flags and joins tend to be subtly wrong.
  • A request that spans both layers ("add a Customer entity for the new CUSTOMER table") is split: import brings in the DB layer, usually along with a default ObjEntity; then adjust the Object layer here.

DbRelationships follow the import settings

Whether DB import owns <dbRelationship> elements depends on <skipRelationshipsLoading> in the DataMap's <dbImport> block. Read it before adding, removing or changing a DbRelationship in a project that uses DB import:

<skipRelationshipsLoading>Who owns DbRelationshipsWhat to do
trueThe user. Import neither reads FKs nor removes relationships from the model.Hand-edit <dbRelationship> elements here, both directions. <dbEntity> / <dbAttribute> still come from import.
false, absent, or no <dbImport> blockDB import. Every FK becomes a relationship; a relationship with no matching FK is dropped by the next import.Don't hand-edit. A relationship backed by an FK comes from cayenne-db-import. For one with no FK in the DB, see below.

When the user wants a relationship that has no FK in the DB and the setting is not true, don't write it and don't change the setting on your own. Explain that the next import would drop it, and offer the two ways out:

  1. Add the FK constraint in the DB, then run cayenne-db-import.
  2. Set <skipRelationshipsLoading>true</skipRelationshipsLoading> in <dbImport> (creating the block if needed) and add the relationship by hand. Spell out the cost: from then on import stops bringing in any relationships, so FKs added to the DB later must also be mapped by hand.

Make the change only after the user picks one.

  • DbRelationship names are not DB metadata. Import matches relationships by their joins, not by name. Renaming them (and keeping the ObjRelationship name in sync) is allowed and belongs to cayenne-model-naming.

Required reading

Read these before making any edit — they describe the XML formats this skill operates on:

  • ${CLAUDE_PLUGIN_ROOT}/references/project-layout.md — locate the project descriptor and DataMaps in the user's repo.
  • ${CLAUDE_PLUGIN_ROOT}/references/datamap-schema.md — every element shape for *.map.xml.
  • ${CLAUDE_PLUGIN_ROOT}/references/project-descriptor-schema.md — cayenne-*.xml shape.

Step 1 — Locate the right file

Follow project-layout.md. If the user has multiple Cayenne projects and the request is ambiguous, ask which one. Cache the answer for the rest of the session.

Check the project-version attribute in the descriptor before editing. If it is lower than the version in project-descriptor-schema.md, the project was saved by an older Cayenne version: stop and hand off to the cayenne-modeler skill so the user can upgrade it in CayenneModeler. Don't edit an old-format file and don't migrate the format by hand — the references here describe the current format only.

Decide whether the change belongs in a DataMap or the project descriptor (table at the end of project-layout.md):

  • Entity/relationship/query/embeddable/procedure → DataMap (*.map.xml).
  • DataMap list, DataNode (DB connection) → project descriptor (cayenne-*.xml).

Step 2 — Make the edit

Apply the change following the schema in datamap-schema.md or project-descriptor-schema.md.

Critical rules

The parts of these rules about writing <dbEntity>, <dbAttribute> and <dbRelationship> elements apply only when the user has opted out of DB import — or, for <dbRelationship> alone, when <skipRelationshipsLoading> is true (see "Who owns what"). Otherwise treat the DB layer as read-only input that the Object layer must reference correctly.

  1. Element order matters. The DataMap schema requires this order inside <dataMap>: <procedure>, <embeddable>, <dbEntity>, <objEntity>, <dbRelationship>, <objRelationship>, the queries (<objectQuery>, <sqlQuery>, <procedureQuery>), <cgen>, <dbImport>. Insert at the right place — don't append blindly.

  2. Cross-link consistently.

    • An <objEntity> references a <dbEntity> by dbEntityName="...". Make sure that DbEntity exists.
    • An <objAttribute> references a DbAttribute by dbAttributePath="COLUMN_NAME". Make sure that column exists on the DbEntity (or on a related one if using a dotted path through a relationship).
    • An <objRelationship> requires a backing <dbRelationship> (or chain of them) via dbRelationshipPath. Never add an ObjRelationship without the DB-layer counterpart. If the DbRelationship is missing and DB import owns relationships (<skipRelationshipsLoading> is not true), it has to come from an FK in the DB via cayenne-db-import — don't write it by hand.
    • When hand-editing the DB layer: most FKs need two <dbRelationship> entries, one per direction. They are not auto-derived.
  3. Use the right type on attributes.

    • dbAttribute type — JDBC type names: VARCHAR, INTEGER, BIGINT, DATE, TIMESTAMP, BOOLEAN, NUMERIC, BLOB, CLOB, VARBINARY, etc. VARCHAR/CHAR/VARBINARY also need length. NUMERIC/DECIMAL also need scale.
    • objAttribute type — Java FQN: java.lang.String, java.lang.Integer, java.util.Date, java.math.BigDecimal, byte[], etc. Use wrapper types (Integer, not int) for nullable columns.
  4. PK handling. PK columns get primaryKey="true" mandatory="true" on the DbAttribute. They are normally not mirrored as ObjAttributes — Cayenne handles them implicitly. Map a PK as an ObjAttribute only if the user wants a "meaningful PK" (visible on the Java side).

  5. Preserve formatting. Match the indentation and quote style of the file (the standard Cayenne style uses tabs and double quotes, but follow what's actually in the file you're editing).

  6. Changing defaultPackage on a DataMap. If the user asks to change the DataMap-level defaultPackage attribute, ask whether entity-level packages should be updated too. Otherwise, every existing objEntity will keep its old package. Ask: "Do you also want me to update the className values on individual <objEntity> elements that currently use the old package?" Update them only if the user confirms.

Step 3 — Validate the edit conceptually

After writing the XML, mentally walk through:

  • Does every objEntity.dbEntityName resolve to an existing <dbEntity>?
  • Does every objAttribute.dbAttributePath resolve to a column on the right DbEntity?
  • Does every objRelationship.dbRelationshipPath resolve to a chain of existing <dbRelationship> entries?
  • If you hand-edited the DB layer (user opted out of DB import): are PK and FK columns marked mandatory="true" where the DB enforces NOT NULL?
  • If the user uses DB import: did the edit leave every <dbEntity> and <dbAttribute> untouched — and every <dbRelationship> too, unless <skipRelationshipsLoading> is true?

If anything fails, fix it before reporting done.

Step 4 — Offer the right next step

  • If you modified entities and the DataMap has a <cgen> block: suggest invoking the cayenne-cgen skill to regenerate Java classes. Mention which entities are affected.
  • If the user added a new entity and there's no Java class yet: same — recommend cayenne-cgen.
  • If the request needs a DB-layer change of any size (a new table, a new or changed column, an FK, syncing with a changed schema) and the user has not opted out of DB import: hand off to cayenne-db-import, or to cayenne-full-db-sync when they want names and classes updated too. Do not script it via XML edits.
  • If the request is about making names descriptive/consistent (cleaning up reverse-engineered names, fixing Gametype/team1-style names, normalizing entity/attribute/relationship names across the model): hand off to cayenne-model-naming — it knows the naming conventions and the rename cross-reference checklist.
  • If the project is in an older format (project-version below the current one): hand off to cayenne-modeler to upgrade it before any edit.
  • If the change is structurally messy (bulk renaming relationships, visual graph rework): suggest the cayenne-modeler skill. Otherwise do not.

Modeler coexistence

CayenneModeler watches the project XML files and automatically detects on-disk changes. When you edit a *.map.xml file directly, the Modeler will prompt the user to reload the project the next time they interact with it. There is no risk of the Modeler silently overwriting your edits. Do not warn the user that the Modeler may overwrite changes or tell them to close the Modeler before editing — that is incorrect and unnecessary.

Anti-patterns

  • Don't upgrade an older project by hand — no bumping project-version or rewriting namespaces and elements yourself. The Modeler runs the real upgrade handlers; use cayenne-modeler.
  • Don't hand-edit the DB layer unless the user explicitly said they don't use DB import. No <dbEntity>, <dbAttribute> or <dbRelationship> additions, removals or attribute changes — not even "just one column". The single carve-out is <dbRelationship> when <skipRelationshipsLoading> is true.
  • Don't flip <skipRelationshipsLoading> to true on your own to make room for a hand-written relationship. It turns off relationship import for the whole DataMap — the user decides. Don't guess the opt-out from the state of the project — when there is no <dbImport> block and no earlier answer, ask once and save the answer. See "Who owns what".
  • Don't hand-edit _<Entity>.java superclass files. They are regenerated by cgen and your changes will be overwritten. Edit the user <Entity>.java subclass instead.
  • Don't add an objRelationship without a dbRelationship. Cayenne will validate-fail at runtime.
  • Don't use primitive Java types (int, long, boolean) as objAttribute type for nullable columns. Primitives can't represent NULL. Use wrappers.
  • Don't reorder existing elements. The schema requires the order documented above; reordering existing elements may also create noisy diffs.
  • Don't run cgen yourself. That's cayenne-cgen's job — invoke that skill instead of calling the MCP tool directly here.
  • Don't suggest mvn cayenne:cdbimport or any Maven/Gradle plugin goal. Those are explicitly out of scope for this plugin.

cayenne-query

Write idiomatic Cayenne 5.0 queries — ObjectSelect, SQLSelect, expressions, prefetch, pagination, aggregates.

Required reading

  • ${CLAUDE_PLUGIN_ROOT}/references/query-api.md — every query mechanism with examples (ObjectSelect, SQLSelect/SQLExec, Expression, ColumnSelect, selecting by id).

Step 1 — Identify the query shape

IntentUse
Fetch one or more entities matching criteriaObjectSelect.query(Cls.class).where(...).select(ctx)
Fetch by primary keyObjectSelect.query(Cls.class).byId(pk).selectOne(ctx)
Aggregate (count, sum)ObjectSelect.query(Cls.class).selectCount(ctx) or ColumnSelect with aggregate functions
One or a few columns only (DTO-style)ObjectSelect.columnQuery(Cls.class, Cls.NAME, Cls.AGE).select(ctx)
Raw SQL with parameter bindingSQLSelect.query(Cls.class, "SELECT ...").params(...).select(ctx)
Insert/update/delete bulkSQLExec.query("UPDATE ...").update(ctx)
Reused named query stored in DataMapXML <objectQuery> / <sqlQuery> / <procedureQuery> (see ${CLAUDE_PLUGIN_ROOT}/references/datamap-schema.md) loaded via NamedQuery

Primary-key lookups: use byId(..) / byIds(..)

When the user is fetching entities by PK, use the ObjectSelect id shorthands rather than ObjectSelect.where(PK.eq(...)):

Artist a = ObjectSelect.query(Artist.class).byId(42).selectOne(ctx);
List<Artist> list = ObjectSelect.query(Artist.class).byIds(1, 2, 3).select(ctx);

Both accept a scalar, a Map<String, Object> of PK column → value (the form for composite PKs), or an ObjectId, and byIds(..) may mix them. SelectById is deprecated — never generate it. If the object is likely already in the context and no query customization is needed, ctx.objectForPK(Artist.class, 42) resolves it from the session cache without a SQL query.

Step 2 — Filter with Property constants

cgen generates Property<T> constants on each entity superclass. Use them — they're type-checked at compile time:

ObjectSelect.query(Artist.class)
    .where(Artist.ARTIST_NAME.likeIgnoreCase("p%"))
    .and(Artist.DATE_OF_BIRTH.between(d1, d2))
    .select(ctx);

Only fall back to ExpressionFactory.matchExp("artistName", ...) or Expression.fromString(...) when:

  • The filter is dynamic (field name comes from runtime input), or
  • The user explicitly wants string-based expressions.

query-api.md lists all common predicate methods on Property.

Step 3 — Handle relationships (prefetch)

When the query traverses a relationship in a loop, always add a prefetch to avoid N+1:

// Bad — fires one query per artist when paintings are accessed
for (Artist a : artists) { a.getPaintings().size(); }

// Good
List<Artist> artists = ObjectSelect.query(Artist.class)
    .prefetch(Artist.PAINTINGS.disjoint())
    .select(ctx);

Pick:

  • .joint() — to-one relationships, or to-many with small fan-out. Single SQL join.
  • .disjoint() — to-many, modest size. Two queries.
  • .disjointById() — to-many, very large parent set. Two queries, keyed by PKs.

Step 4 — Apply ordering, paging, and caching as needed

ObjectSelect.query(Artist.class)
    .orderBy(Artist.ARTIST_NAME.asc())
    .pageSize(50)             // server-side pagination
    .limit(1000)
    .localCache()             // per-context cache, or .sharedCache("group-name")
    .select(ctx);

Use sharedCache for reference data (rarely changes, read often). Use pageSize to avoid loading entire result sets.

Step 5 — Raw SQL when needed

List<Artist> hits = SQLSelect.query(Artist.class,
        "SELECT * FROM ARTIST WHERE ARTIST_NAME LIKE #bind($pattern)")
    .params(Map.of("pattern", userInput + "%"))
    .select(ctx);

Always use #bind($name) placeholders. Never concatenate user input into SQL. Cayenne's SQLTemplate is Velocity-based — see query-api.md for #bind, #bindEqual, #chain, and adapter-specific SQL with <sql adapterClass="...">.

Anti-patterns

  • Parameter String concatenation in raw SQL. Use #bind($name). Concatenation is a SQL injection vector and may also result in invalid syntax.
  • Using selectOne when multiple may match. It throws. Use selectFirst if "any one" is okay.
  • Loading large result sets without pagination. Use .pageSize(n) or iterator() and process incrementally.
  • N+1 from missing prefetch. If iterating entities and accessing relationships per-entity, add .prefetch(...).
  • Using Expression.fromString(...) or ExpressionFactory.matchExp("fieldName", ...) for static queries. Prefer typed Property constants (Artist.ARTIST_NAME.eq(...)) — they catch typos at compile time and survive model refactors.
  • Mutating fetched objects without committing. ObjectContext.commitChanges() is required for changes to persist.

cayenne-runtime

Bootstrap CayenneRuntime and use ObjectContext for CRUD in a Java application.

Required reading

  • ${CLAUDE_PLUGIN_ROOT}/references/runtime-api.md — CayenneRuntimeBuilder methods, ObjectContext API, transaction patterns, lifecycle rules.

Step 1 — Find or create the bootstrap site

Where does the user's app construct CayenneRuntime? Common patterns:

  • Plain Java / CLI — a main() method or a singleton holder.
  • Bootique app — typically a @Provides method in a module (provideCayenneRuntime(@Inject DataSource ds)). If editing a Bootique app, mention that the java-dev:bootique-config skill (if available) can help with the surrounding config wiring.
  • Spring app — a @Bean CayenneRuntime cayenneRuntime(DataSource ds) method in a configuration class.
  • Cayenne-only embedded — a static field or DI singleton initialized lazily.

If none exists yet, create one. Apply runtime-api.md patterns:

CayenneRuntime runtime = CayenneRuntime.of()
        .addConfig("cayenne-mydb.xml")
        .dataSource(externalDataSource)   // or .url(...).jdbcDriver(...).user(...).password(...)
        .build();

Step 2 — Decide on the DataSource path

Two paths from CayenneRuntimeBuilder:

WhenUse
Production app with Spring/Bootique/Hikari already managing the pool.dataSource(ds) — Cayenne reuses the external pool.
Standalone tool or test fixture with no external DI.url(...).jdbcDriver(...).user(...).password(...) — Cayenne's built-in pool.

The .dataSource() path is preferred when possible. Never put JDBC credentials in cayenne-*.xml for production code — keep them in the application's normal config mechanism.

Step 3 — Use ObjectContext

ObjectContext ctx = runtime.newContext();   // one per request/thread
Artist a = ctx.newObject(Artist.class);
a.setArtistName("Picasso");
ctx.commitChanges();

Rules:

  • CayenneRuntime is a heavy singleton — create once, share for app lifetime, call shutdown() on exit.
  • ObjectContext is not thread-safe — new one per request/thread.
  • Don't mix objects across contexts. Use ctx.localObject(other) to bring an object into the current context.

Step 4 — Transactions

commitChanges() is auto-transactional. For multi-step transactions:

runtime.performInTransaction(() -> {
    // multiple commits in one transaction
    return null;
});

Any throw rolls back the whole block.

Step 5 — Verify the integration

Tell the user how to smoke-test:

  1. Build and run the app.
  2. From a request handler: ObjectContext ctx = runtime.newContext(); long count = ObjectSelect.query(SomeEntity.class).selectCount(ctx); — should return a number without throwing.

If they hit CayenneRuntimeException: No DataNode..., the descriptor's <map> reference doesn't have a node — confirm the DataSource wiring went through CayenneRuntimeBuilder.dataSource(...) (Cayenne synthesizes a node from this).

Anti-patterns

  • Creating CayenneRuntime per request. It's a heavyweight singleton. Cache it for the application lifetime.
  • Sharing ObjectContext across threads. Not safe. Create one per thread.
  • Putting DB credentials in cayenne-*.xml for production. Use the application's secret management; pass a DataSource to the builder.
  • Forgetting commitChanges(). Mutations stay in memory until commit.
  • Forgetting shutdown() on app exit. Hangs the JVM on some pool implementations.

Sponsors

Details

Marketplace
apache/cayenne
Source
ai-plugin
Author
Apache Cayenne
Category
Development

More from apache/cayenne

All 2