
apache-cayenne-6
Apache Cayenne 6.0 ORM — design DataMaps, reverse-engineer schemas, generate classes, write runtime code.
- GitHub stars
- 348
Install
/plugin install apache-cayenne-6@apache-cayenneRun it inside Claude Code after adding the marketplace with /plugin marketplace add apache/cayenne.
Contents
Discovered from sourceSkills 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_runtool 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.filesConsideredandsummary.filesWrittenverbatim — 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, an error in a custom template, 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 (viacayenne-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>.javasuperclass files were generated, gently remind the user not to edit those — they will be overwritten next run. User code goes in the matching<Entity>.javasubclass. - If the user just ran reverse engineering, this skill is the natural follow-up. Cross-link back to
cayenne-modelingif they need to tweak names/types before regenerating.
Anti-patterns
- Do not pre-check the DataMap for a
<cgen>block before callingcgen_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>.javafiles. Generated superclasses. Edit<Entity>.javasubclasses. - Do not confuse
projectPathanddataMaparguments.projectPathis a file system path tocayenne-*.xml.dataMapis a logical name (e.g.mydb), not a path tomydb.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_runandopen_projecttool 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 viacayenne-modeling. Withfalse(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 — namespacehttp://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 thesummarycounters (entities added/removed/modified, relationships added) to the user. Call out a non-zeroentitiesRemovedexplicitly — 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 theerror.messageand the partialsummary.validation_failed— a pre-flight check failed. Use theerror.codeto guide next steps (see below).
Validation failures and their remediation
| Code | What failed | What to do |
|---|---|---|
project_not_found | Project path not readable | Verify path. |
project_parse_failed | File is not a valid Cayenne descriptor | Confirm the file is a cayenne-*.xml. |
datamap_not_found | DataMap name not in project | The error message lists available names; use one. |
dbconnector_not_configured | No connection saved for this DataMap | → Go to Step 4 to configure via the Modeler dialog. |
jdbc_driver_not_loadable | Driver jar not on the Modeler classpath | Open CayenneModeler → Preferences → Classpath, add the driver jar, save, then re-run. |
jdbc_connection_failed | Connection could not be opened | Check 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:
- DataMap → DB Import tab
- 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.
- JDBC Driver — e.g.,
- Configure screen — set table/column/procedure filters:
- Include/exclude regex patterns under the relevant catalog/schema.
- Table Types — usually
TABLE; addVIEWif needed.
- Naming screen:
- Naming Strategy, Strip from Table Names, Default Package, Meaningful PK Tables.
- See
dbimport-config.mdfor what each does.
- Other Options — toggles for
skipPrimaryKeyLoading,skipRelationshipsLoading, etc. - 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-cgento regenerate Java classes for the new/changed entities. Quote the DataMap name so the cgen skill can pass it tocgen_run. - If the imported names look awkward (run-together words,
team1-style relationship names, a table prefix leaking into relationships), you can offer thecayenne-model-namingskill 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 Gradlecdbimporttask, or hand-running thecayenne-dbsyncJava APIs.dbimport_runis 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/forceDataMapSchemadefensively. 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.mdand stop. - Do not run the import through the Modeler GUI dialog when
dbimport_runis 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:
cayenne-db-import— import DB schema metadata into the DataMap (the mapping XML).cayenne-model-naming— polish the Object-layer names of what the import just added.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), viaproject-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:
importedwith a non-emptysummary(entities/relationships added/modified) → the model changed. Proceed to Step 2.up_to_date(orimportedwith 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_runis idempotent and simply reports everything skipped if the code is already current. Tell the user the model was already up to date.validation_failed→ followcayenne-db-import's remediation table for theerror.code. The common first-run case isdbconnector_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) → surfaceerror.messageand 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_runsummary). - 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/errorstops the pipeline;up_to_dateskips 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:cgenor the Gradle tasks. The sub-skills use the MCP tools exclusively; if the server isn't connected, they point atcayenne-mcp-server/README.mdand 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 diffis 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:
- Run-together names with no separators —
gametype→GameType,dateofbirth→dateOfBirth. Split on a real word boundary you're confident about; never invent one. - 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_IDsuffix (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_idreferencingaa_team→homeGamestoo). 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_IDsuffix and collapsed toemployee/employee1. - 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, notaaOrders); 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. - 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/objectIdare 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, everyobjRelationshipsource/target, queryrootName,resultEntity. - ObjRelationship → prefetch/expression paths (its
dbRelationshipPathis unaffected). - ObjAttribute → qualifier/ordering paths (its
dbAttributePathis unaffected). - DbRelationship → every
dbRelationshipPathsegment 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,dbRelationshipPathsegment, andclassNamestill resolve? - Hand off to
cayenne-cgento (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.javafiles 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→GameTypeonly 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 relationshipsource/targetand queryrootName. - Don't rename a DbRelationship without fixing every
dbRelationshipPathsegment, 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/dbRelationshipPathtargets. 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_projecttool 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:
- Create a minimal descriptor first (use
cayenne-modelingto scaffold it), then open. - 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:
| Code | Meaning |
|---|---|
ok | Modeler launched and loaded the project. |
modeler_not_found | The MCP jar is not co-located with a Modeler installation. User needs to install CayenneModeler properly. |
project_not_found | The projectPath doesn't exist or isn't readable. |
handshake_timeout | The 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_failed | Process 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-versionis 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 rewritescayenne-*.xmland every*.map.xmlin 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-importskill'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(viadbimport_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-modelingskill handles most modeling intent. - Do not retry
open_projectonhandshake_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 -jardirect calls, no opening a.dmg, noopen -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 model | Owner | How to change it |
|---|---|---|
DB layer — <dbEntity>, <dbAttribute> (type, length, scale, mandatory, PK flags), <dbRelationship> and its joins | The database, via DB import | Change 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, callbacks | The user | Hand-edit here. |
Everything else — queries, <embeddable>, <procedure>, <cgen>, <dbImport> filters, the project descriptor | The user | Hand-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:
- The user already said — in the request, earlier in the session, in project instructions, or in your persistent memory for this project. Follow that.
- The target DataMap has a
<dbImport>block — the project uses DB import. Don't ask. - 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_runmerges 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
Customerentity for the newCUSTOMERtable") 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 DbRelationships | What to do |
|---|---|---|
true | The 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> block | DB 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:
- Add the FK constraint in the DB, then run
cayenne-db-import. - 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-*.xmlshape.
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.
-
Element order matters. The DataMap schema requires this order inside
<dataMap>:<comment>,<embeddable>,<procedure>,<dbEntity>,<objEntity>,<dbRelationship>,<objRelationship>, the queries (<objectQuery>,<sqlQuery>,<procedureQuery>),<dbImport>,<cgen>. Insert at the right place — don't append blindly. A<comment>always goes first in its element, seedatamap-schema.md. -
Cross-link consistently.
- An
<objEntity>references a<dbEntity>bydbEntityName="...". Make sure that DbEntity exists. - An
<objAttribute>references a DbAttribute bydbAttributePath="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) viadbRelationshipPath. Never add an ObjRelationship without the DB-layer counterpart. If the DbRelationship is missing and DB import owns relationships (<skipRelationshipsLoading>is nottrue), it has to come from an FK in the DB viacayenne-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.
- An
-
Use the right
typeon attributes.dbAttribute type— JDBC type names:VARCHAR,INTEGER,BIGINT,DATE,TIMESTAMP,BOOLEAN,NUMERIC,BLOB,CLOB,VARBINARY, etc. VARCHAR/CHAR/VARBINARY also needlength. NUMERIC/DECIMAL also needscale.objAttribute type— Java FQN:java.lang.String,java.lang.Integer,java.util.Date,java.math.BigDecimal,byte[], etc. Use wrapper types (Integer, notint) for nullable columns.
-
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). -
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).
-
Changing
defaultPackageon a DataMap. If the user asks to change the DataMap-leveldefaultPackageattribute, ask whether entity-level packages should be updated too. Otherwise, every existingobjEntitywill keep its old package. Ask: "Do you also want me to update theclassNamevalues 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.dbEntityNameresolve to an existing<dbEntity>? - Does every
objAttribute.dbAttributePathresolve to a column on the right DbEntity? - Does every
objRelationship.dbRelationshipPathresolve 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>istrue?
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 thecayenne-cgenskill 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 tocayenne-full-db-syncwhen 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 tocayenne-model-naming— it knows the naming conventions and the rename cross-reference checklist. - If the project is in an older format (
project-versionbelow the current one): hand off tocayenne-modelerto upgrade it before any edit. - If the change is structurally messy (bulk renaming relationships, visual graph rework): suggest the
cayenne-modelerskill. 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-versionor rewriting namespaces and elements yourself. The Modeler runs the real upgrade handlers; usecayenne-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>istrue. - Don't flip
<skipRelationshipsLoading>totrueon 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>.javasuperclass files. They are regenerated by cgen and your changes will be overwritten. Edit the user<Entity>.javasubclass instead. - Don't add an
objRelationshipwithout adbRelationship. Cayenne will validate-fail at runtime. - Don't use primitive Java types (
int,long,boolean) asobjAttribute typefor 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:cdbimportor any Maven/Gradle plugin goal. Those are explicitly out of scope for this plugin.
cayenne-query
Write idiomatic Cayenne 6.0 queries — ObjectSelect, SQLQuery, expressions, prefetch, pagination, aggregates.
Required reading
${CLAUDE_PLUGIN_ROOT}/references/query-api.md— every query mechanism with examples (ObjectSelect incl. column queries, SQLQuery, Expression, selecting by id).
Step 0 — Check the Cayenne version
This plugin is for Cayenne 6.0. Look at the project's build file first: if it depends on Cayenne 5.x, the API below
doesn't apply. Tell the user to install apache-cayenne-5@apache-cayenne instead, and stop.
Step 1 — Identify the query shape
| Intent | Use |
|---|---|
| Fetch one or more entities matching criteria | ObjectSelect.query(Cls.class).where(...).select(ctx) |
| Fetch by primary key | ObjectSelect.query(Cls.class).byId(pk).selectOne(ctx) |
| Aggregate (count, sum) | ObjectSelect.query(Cls.class).selectCount(ctx) or ObjectSelect.query(Cls.class).columns(..) with aggregate functions |
| One or a few columns only (DTO-style) | ObjectSelect.query(Cls.class).columns(Cls.NAME, Cls.AGE).select(ctx) |
| Raw SQL with parameter binding | SQLQuery.query(Cls.class, "SELECT ...").params(...).select(ctx) |
| Insert/update/delete bulk | SQLQuery.query("UPDATE ...").update(ctx) |
| Reused named query stored in DataMap | XML <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 no longer exists — 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 = SQLQuery.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 SQL templates use a Velocity-like directive syntax — 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
selectOnewhen multiple may match. It throws. UseselectFirstif "any one" is okay. - Loading large result sets without pagination. Use
.pageSize(n)oriterator()and process incrementally. - N+1 from missing prefetch. If iterating entities and accessing relationships per-entity, add
.prefetch(...). - Using
Expression.fromString(...)orExpressionFactory.matchExp("fieldName", ...)for static queries. Prefer typedPropertyconstants (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—CayenneRuntimeBuildermethods,ObjectContextAPI, transaction patterns, lifecycle rules.
Step 0 — Check the Cayenne version
This plugin is for Cayenne 6.0. Look at the project's build file first: if it depends on Cayenne 5.x, the API below
doesn't apply. Tell the user to install apache-cayenne-5@apache-cayenne instead, and stop.
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
@Providesmethod in a module (provideCayenneRuntime(@Inject DataSource ds)). If editing a Bootique app, mention that thejava-dev:bootique-configskill (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")
.defaultDataNode(dataSource) // any javax.sql.DataSource, or a DataNodeDescriptor
.build();
Step 2 — Decide on the DataSource path
The project XML lists DataMaps only; the connection is always wired in code, as the DataSource of a DataNode:
| When | Use |
|---|---|
| Production app with Spring/Bootique/Hikari already managing the pool | .defaultDataNode(ds) — Cayenne reuses the external pool. |
| Standalone tool or test fixture with no external DI | CayenneDataSource.of(url).userName(..).password(..).pool(min, max).build() — Cayenne's built-in pool, passed to .defaultDataNode(..). |
| A node that needs a stable name, a pinned adapter or schema creation on startup | DataNodeDescriptor.of("name").dataSource(ds).createSchemaIfNeeded().build(), passed to .defaultDataNode(..) or .addDataNode(.., "map1", "map2"). |
Prefer the external DataSource when the app has one. Never put JDBC credentials in source control — 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:
CayenneRuntimeis a heavy singleton — create once, share for app lifetime, callshutdown()on exit.ObjectContextis 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:
- Build and run the app.
- 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.defaultDataNode(...), or that addDataNode(..) lists that map.
Anti-patterns
- Creating
CayenneRuntimeper request. It's a heavyweight singleton. Cache it for the application lifetime. - Sharing
ObjectContextacross threads. Not safe. Create one per thread. - Putting DB credentials in
cayenne-*.xmlfor production. Use the application's secret management; pass aDataSourceto 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