Praxis Java Resource Authoring
Build a resource as a governed semantic contract, not as a controller plus an
incidental CRUD screen. The canonical baseline is resource + surfaces + actions + capabilities; every projection must remain backed by an executable operation.
Inspect Before Authoring
Read the host's AGENTS.md, the affected domain documentation, entity/query
source, existing resource keys and paths, controller/service/mapper, DTOs,
filters, tests, and direct consumers. In the starter, inspect the resource base,
schema resolution, and discovery contracts before adding a host convention.
Classify the work as local-pequena, transversal, contrato-publico, or
arquitetural. For a proposed field, endpoint, action, surface, capability,
lookup, stat, export, or metadata shape, classify adherence as
ja-suportado-so-ux, ja-suportado-mal-nomeado-ou-mal-materializado,
suportado-parcialmente, or lacuna-real-de-contrato.
Only a real contract gap justifies a new platform contract. The quickstart is operational proof, never the canonical owner of a starter or runtime semantic.
Compose The Resource
- Establish stable identity:
@ApiResource(resourceKey=...), the canonical path constant,@ApiGroup, resource intent, and a semantic name independent of a label or database table. Treat a path/key change as a public identity migration across schemas, links, option sources, actions, surfaces, tests, HTTP examples, and consumers. - Choose the smallest resource base that matches real operations (with exact generic parameter order):
- read-only query/view:
BaseCrudRepository<E, ID>ResourceMapper<E, ResponseDTO, ?, ?, ID>AbstractReadOnlyResourceService<E, ResponseDTO, ID, FilterDTO>(IDis 3rd)AbstractReadOnlyResourceController<ResponseDTO, ID, FilterDTO>(noE,IDis 2nd)
- standard mutable resource:
BaseCrudRepository<E, ID>ResourceMapper<E, ResponseDTO, CreateDTO, UpdateDTO, ID>(Eis 1st,IDis 5th;applyUpdate(E entity, UpdateDTO dto)takesentity1st)AbstractBaseResourceService<E, ResponseDTO, ID, FilterDTO, CreateDTO, UpdateDTO>(Eis 1st,IDis 3rd; callsuper(repository, Entity.class)and overridegetResourceMapper(),getDatasetVersion(),getStatsFieldRegistry(), andStatsSupportMode.AUTOmethods)AbstractResourceController<ResponseDTO, ID, FilterDTO, CreateDTO, UpdateDTO>(noE,IDis 2nd; annotate with@ApiResource(value=..., resourceKey=..., title=..., description=..., icon=..., identity=@ResourceIdentity(...), quickFilters={...})and@ApiGroup(...); overridegetService()andgetResponseId(dto))
- create/update-only, unit-delete, or collection-command-only (
AbstractCollectionCommandResourceController): use the canonical specialized base only when the resource genuinely lacks the omitted operation. - Composite Primary Keys (
@EmbeddedId/CompositeResourceId): When a resource has an immutable composite business key (e.g.,EmployeeAssignmentId(Long employeeId, Integer assignmentNumber)orOrderItemId(Long orderId, Integer lineNumber)), model it as an@Embeddablerecord implementingCompositeResourceIdand pass it directly asIDinBaseCrudRepository<E, EmployeeAssignmentId>,ResourceMapper<..., EmployeeAssignmentId>,AbstractBaseResourceService<..., EmployeeAssignmentId, ...>, andAbstractResourceController<..., EmployeeAssignmentId, ...>. The starter automatically serializes/deserializesEmployeeAssignmentIdas a canonical wire string ("1001:1") across path variables, query parameters (ids,includeIds),OptionDTO<EmployeeAssignmentId>,RESOURCE_ENTITYoption sources (valuePropertyPath = "id"),@Filterable(relation = "id.employeeId")/@Filterable(relation = "assignment.id"), compositeSortexpansion (sort=id,desc), tabular exports, and/schemas/filtered(type: "string",format: "composite-id",x-ui.compositeIdComponents,x-ui.compositeIdSeparator). Ordinary@Embeddableclasses used with@Embedded(value objects) do not implementCompositeResourceIdand remain structured JSON objects while still navigating via.get(part)in JPA Criteria without erroneous joins. For optimal UX in@praxisui/*tables and forms: expose bothEmployeeAssignmentId idand the individual business columns (employeeId,assignmentNumber) inResponseDTO; expose separate editable business fields inCreateDTO(employeeId,assignmentNumber) and constructnew EmployeeAssignmentId(...)inResourceMapper.newEntity; and omit or mark PK fieldsreadOnly = trueinUpdateDTO(applyUpdatenever mutatesentity.setId(...)). Conversely, when a table's natural key includes mutable attributes that users edit inPUT /{id}(e.g.,TimesheetEntrywhereentryDateandactivityCodeare editable), use an immutable surrogate PK (Long id) +UNIQUEconstraint on the natural columns because JPA forbids mutating@EmbeddedIdcomponents on a managed entity. Do not start new work on legacy CRUD/service hierarchies. For a complete copy-paste compiling slice, seepraxis-java-host-project/references/resource-baseline.md.
- read-only query/view:
- Define operation-specific response, create, update, filter, and explicit
command DTOs.
@Schemadescribes verified business meaning;@UISchemadescribes presentation/control behavior; governance and AI-use metadata are deliberate. A filter models predicates, not a reduced create DTO.- 100% Entity Column Accounting, 20-Pillar Completeness & 3-Phase Execution Gate: Consult
META-INF/praxis/AI-RESOURCE-BLUEPRINT.md(orpraxis-metadata-starter/docs/guides/GUIA-00-BLUEPRINT-COMPLETO-RECURSO-PRAXIS.md). Never truncate a 20- to 55-column enterprise entity into an 8-field skeletal DTO or a 3-fieldFilterDTO, and never attempt all layers of a multi-resource module in a single shallow pass. Execute in 3 vertical phases with 100% depth:- Phase 1 (Data, DTOs,
@UISchema,@MicroVisualization, Quick View 360°, Rich Lookups &FilterDTO): 100% entity business columns inResponseDTO(with 5–10 visible columns in the main table and secondary fields under@UISchema(group = ..., tableHidden = true)), short@UISchema.label(≤ 35 chars, no trailing period),@MicroVisualization+@Threshold,@DomainGovernance+fieldAccess, rich@ResourceIdentity(subtitleField,metadataFields), 4–8quickViewVisiblefields,@ResourceReferencewithpreviewSurfaceIdon the resource title and all FK display fields, richEntityLookupDescriptor(LookupSelectionPolicy,LookupDetailDescriptor,LookupDisplayDescriptor,LookupFilteringDescriptor,dependsOn/dependencyFilterMap), and an exhaustiveFilterDTO+@QuickFilters +ResourceFilterAccessScope(including at least one broad/omnibox search field with@Filterable(operation = FilterOperation.LIKE, relations = {"fullName", "socialName", "motherName", "dependents.fullName", "taxId"}), multi-operator combinations on the same attribute such asLIKE+STARTS_WITH+EQUAL+INandBETWEEN+IN_LAST_DAYS+IN_NEXT_DAYS, completeness filtersIS_NULL/IS_NOT_NULL, collection cardinalitySIZE_GT/SIZE_EQ, and multi-level cross-entity pathsrelation = "a.b.c"). - Phase 2 (Surfaces, New Cross-Entity Endpoints, Intents, Workflow Actions, Governed Bulking Beyond the Obvious, Facts, Analytics & Export):
@UiSurface(READ_PROJECTIONfor Quick View 360° and child collectionsrelatedChildResourceKey,PARTIAL_FORMpaired with@ResourceIntent, andVIEW), new dedicated read-only projection endpoints (AbstractReadOnlyResourceController) when entity relationships reveal non-obvious analytical/operational views (e.g., vacancy/occupancy matrices, expiring-items radar, compliance audits), full lifecycle@WorkflowActions withIf-Match/Idempotency-Key, Governed Bulking across all 3 modes beyond obvious columns (audit 100% of mutable fields: enableBulkMode.UNIFORM_UPDATEon all collective standardization fields such as unit, cost center, shift, regime/plan, payment/bank, manager, and flags; enableBulkMode.PER_ITEM_UPDATEbroadly on inline batch-grid revision fields such as phones, emails, addresses, bank accounts, individual amounts/limits, external codes, and per-item dates; and discover collectiveBulkMode.DOMAIN_COMMAND@WorkflowAction(scope = ActionScope.COLLECTION)transitions from the entity lifecycle and relationships such as batch relocation, batch approval/homologation, batch suspension/reactivation, or parametric revision),@ResourceFacts (shortlabel≤ 35 chars),StatsFieldRegistry+@UiAnalytics/@AnalyticsProjection, andCollectionExport(CSV,JSON,EXCELwithCollectionExportFieldPresentation). - Phase 3 (Transactional Invariants, Reactive Determinations, Rules Engine & Automated Gates): transactional domain invariants (
409/422withfieldErrors),ReactiveDeterminationDefinitionProvider(POST /{resource}/reactive-determinations/evaluate), deterministicpraxis-rules-engineRuleSets (andpraxis-config-starterGOVERNED_DECISIONsnapshots when active), N+1 cold query-count assertions, native JUnit completeness gate (SemanticMetadataReviewer+PraxisExpressionStaticValidator+OptionSourcePublicationInventory), andpython scripts/workspace/audit-java-resource-completeness.py <host> --strict.
- Phase 1 (Data, DTOs,
- 100% Entity Column Accounting, 20-Pillar Completeness & 3-Phase Execution Gate: Consult
- Implement mapper, service, validation, transactions, and controller as one
coherent slice. Preserve
RestApiResponse, canonicalidField, and_links; do not introduce host envelopes, endpoint aliases, string-built schema maps, or frontend-only id fixes.ResourceMapper.applyUpdatemust preserve identity loaded from the route. MapStruct update methods over@MappingTargetmust ignoreidand every route-owned technical key, or use an equivalent deliberate mapper contract. A missing or divergent payload id never clears, replaces, or repairs the managed entity identity; do not reinsert it in Angular or after the mapper. Resource generators and scaffolds must emit this rule and keep a focused generated-source gate that rejects technical-identity assignment in update merges. Audit lifecycle fields in create, update, inherited DTOs, mappers and internal Java writers. A guarded workflow action is ineffective when a cadastral path can set the same status/reason. Keep business transitions in their action boundary; reject forbidden values explicitly instead of silently reporting a successful ignored write. Validate both HTTP binding and direct Java calls, protect merge targets, and prove legitimate cadastral edits still work. Initial state belongs to the domain: choose it from the existing lifecycle and prove the activation/signing journey; do not invent a permissive default. A lock query can return a previously managed stale instance: refresh under the same lock before deciding the transition. Bound lock acquisition and test the actual PostgreSQL behavior; mocks do not prove serialization.- Publishing an item ETag alone does not opt the inherited PUT into If-Match. Use
VersionedCreateUpdateResourceService(precondition.requireMatchon the managed persisted version before applying the mapper, paired body/ETag viaResourceRepresentationResult/getEntityResourceVersion(entity)). For structural bulk CRUD update (@BulkResourceOperations,@BulkEditable,BulkFieldChanges,bulk-update/bulk-update-items), read bulk-crud-update-and-versioned-put.md.
- Publishing an item ETag alone does not opt the inherited PUT into If-Match. Use
- Add relations only through governed option/lookup contracts. A resource entity
lookup must prove its source key,
x-ui.optionSource, filter endpoint, selected-value reload, dependencies, authorization, and human display value. - Model an explicit business transition as
@WorkflowAction, with request and response schemas, state/authorization checks, negative paths, and capability discovery. Model a composed journey as@UiSurface. Do not hide either in a generic update, method name, or UI button; do not combine action and surface on one method without reviewing conflict validation. - Add capabilities, availability, stats, export, governance, or related
resources only when the domain operation exists and the relevant canonical
contract is fully backed.
/capabilitiesaggregates availability; it is not an alternate schema or payload definition. - For tenant-specific JSONB extensibility (
custom_fields+custom_field_definitions), map the entity column with@JdbcTypeCode(SqlTypes.JSON), annotateMap<String, Object> customFieldswith@CustomFields(resourceKey = ...)onResponseDTO,CreateDTO,UpdateDTO, andFilterDTO, and register aCustomFieldDefinitionProviderbean so/schemas/filtered, server-side validation,/filterJSONB predicates,/export, and/schemas/domainmaterialize tenant custom fields canonically. For derived business facts/indicators in/schemas/domain, annotate the resource with@ResourceFactor provide aResourceFactCatalogProviderbean. - Audit
CreateDTO,UpdateDTO, and entity relationships for Reactive Determinations (ReactiveDeterminationDefinitionProvider— Beyond the Obvious) across four families: (a) cross-entity lookup/directory projections ("/postalCode"-> address fields,"/positionId"-> salary floor/schedule/vacancies); (b) multi-field deterministic formulas ("/grossSalary"+"/baseDeductions"->"/netSalary","/startDate"+"/probationDays"->"/expectedEndDate"); (c) chained determinations (A -> B -> Cwhere an output of Determination 1 triggers Determination 2); and (d) draft policy/eligibility/capacity previews. Declare all output fields onCreateDTO/UpdateDTO, annotatecreate/updateand the non-persistingPOSTdetermination endpoint with explicit@Operation(operationId = ...), and followpraxis-reactive-determinations.
Read resource-delivery-matrix.md when planning a resource packet, selecting a proof, or deciding whether an optional enterprise feature belongs in this delivery.
Preserve Canonical Boundaries
praxis-metadata-starterowns annotations, resource bases,/schemas/filtered,x-ui, surfaces, actions, capabilities, option-source contracts, and HATEOAS.praxis-config-starterowns governed decision authoring and config persistence. A host may consume an applied materialization but must not recreate its authoring, publication, or inference lifecycle.praxis-ui-angularis the runtime consumer. When a resource publishes a public metadata/discovery change, prove its materializability through the relevant schema, option, surface/action/capability, error, and stats/export consumer path rather than assuming a browser will infer it.
Do not choose semantic scope or execute primary intent through labels, aliases, keyword lists, route fragments, regexes, or fuzzy matching. Use resource keys, schemas, actions, surfaces, capabilities, governed catalogs, and declared tools; text can only help rank already-scoped candidates.
Produce Evidence, Not Just Files
Before editing a transversal, contrato-publico, or arquitetural resource,
record the canonical owner, affected consumers, public/derived artifacts, focused
tests, and beta migration/breaking risk. For a legacy-backed development
migration, mutations authorized by the process can be performed, but retain a
scoped probe, before/after evidence, and cleanup or rollback plan.
Prove the smallest complete path:
- resource base, CRUD, identity, and
_links: focused starter or host resource tests, including update with absent and divergent payload ids followed by a read proving that the route identity stayed stable; for generated resources, inspect or assert the generated update implementation so it cannot assign a route-owned technical key; - schema/
x-uicontract:/schemas/filteredand operation resolution proof; - lookup: filter and by-ids, including dependency and selected-value reload;
- action/surface/capability: positive and negative availability/discovery proof;
- public metadata change: quickstart HTTP proof and relevant Angular consumer tests or an explicit reason they are unaffected.
Review docs, OpenAPI/HTTP corpus, quickstart pilots, and Angular materialization only when the published contract they mirror changes. State explicitly when no derived artifact applies.
Companion Skills
praxis-metadata-resource-baseline: resource hierarchy, response envelope, HATEOAS, filters, stats, and export base behavior.praxis-dto-annotations: semantic, UI, governance, AI, filter, and lookup annotations on DTOs.praxis-metadata-schema-contracts:/schemas/filtered, schema references, OpenAPI, ETag, andX-Schema-Hash.praxis-metadata-discovery-capabilities: actions, surfaces, availability, capabilities, cockpit, stats, and export discovery.praxis-metadata-domain-option-sourcesandpraxis-resource-entity-lookup-backend: domain governance and option-source implementation.praxis-reactive-determinations: step-by-stepReactiveDeterminationDefinitionProviderauthoring, compiler invariants, and chained form determinations.praxis-java-host-project: host bootstrap, dependencies, and local project integration.
Close with the resource packet, resolved classifications, canonical owner, operation matrix, tests run, consumer proof, and outstanding platform gap. A resource is not complete because its controller compiles; it is complete when its semantic contract is discoverable and its intended operation is proven.
For clean-context write guards, include create as well as update/actions. The base resource create path may query through its mapper and flush the entire persistence context; checking only beforeCreate can be too late. Reject caller-owned dirty or unbound contexts before the first mapper/repository/policy operation, including the NEVER_APPLIED policy branch. Prove that rejected creates do not flush unrelated managed lifecycle changes.