
shipwithai-java-backend-toolkit
Guardrail-first Spring Boot + JPA toolkit. Just-in-time hooks catch missing @Version, broken @Transactional proxies, entity-in-controller leaks, N+1, and query injection as you write them; scaffold skills generate correct-by-default entities, endpoints, and migrations; a tuned reviewer agent shares one ruleset with the hooks.
- version
- 0.1.0
- GitHub stars
- 9
Install
/plugin install shipwithai-java-backend-toolkit@shipwithaiRun it inside Claude Code after adding the marketplace with /plugin marketplace add ShipWithAI/shipwithai-plugins.
Contents
Discovered from sourceSkills 11
DB Migration — Scaffold
Keeps schema and entities in lockstep: every entity/schema change ships with a
migration. Never rely on ddl-auto: update in shared environments.
Step 1 — Detect the migration tool
| Tool | Signal |
|---|---|
| Flyway | flyway-core dependency, or a src/main/resources/db/migration/ directory |
| Liquibase | liquibase-core dependency, or a src/main/resources/db/changelog/ directory |
If neither is present, ask which to set up (default Flyway — simplest for v1), and note the dependency the project must add.
Step 2 — Determine the next version
- Flyway: scan
db/migration/forV<n>__*.sql, takemax(n) + 1. Filenames:V<n>__<snake_case_description>.sql. - Liquibase: find the changelog (
db.changelog-master.*), add a new changeset with a unique incrementingidand the project's author convention.
Step 3 — Render the migration
From assets/, substitute {{VERSION}}, {{DESCRIPTION}}, {{TABLE_NAME}},
{{AUTHOR}}:
- Flyway:
flyway_migration.sql.tmpl→db/migration/V{{VERSION}}__{{DESCRIPTION}}.sql - Liquibase:
liquibase_changeset.xml.tmpl→ appended/included into the master changelog
The DDL must include the columns the guardrails imply for entities: a version
column (optimistic lock) and audit columns (created_at, updated_at) when the
entity extends the audited base.
Step 4 — Report
Show the migration path + the SQL/changeset. If invoked standalone, remind the user to keep the entity and migration in the same commit.
Failure modes — do NOT
- Do NOT reuse an existing version number (Flyway will refuse; checksums break).
- Do NOT mix Flyway and Liquibase in one project.
- Do NOT edit an already-applied migration — add a new one (immutable history).
- Do NOT forget the
version/ audit columns when the entity uses them.
Idempotent Endpoint — Scaffold
Unsafe POSTs get retried — by clients, proxies, and message queues. Without
idempotency a retry charges the card twice or creates two orders. This scaffolds a
filter that makes a retry carrying the same Idempotency-Key replay the original
response, so the side effect happens exactly once.
Step 1 — Detect conventions (do not assume)
Read before generating:
- Existing filter chain: look for
OncePerRequestFilter/FilterRegistrationBeanconfig and a….web/….configpackage; place the filter there and register it the same way the project registers other filters. - Storage available: check for Redis (
spring-data-redis) or a relational DB. The filter depends only on theIdempotencyStoreSPI — pick the backing store that already exists; do not add a new datastore. - Existing idempotency: if the project already keys retries somewhere, extend that instead of adding a parallel mechanism.
Step 2 — Render templates
From assets/, substitute {{PACKAGE}}:
IdempotencyStore.java.tmpl→<pkg>/web/idempotency/IdempotencyStore.java(the SPI)IdempotencyKeyFilter.java.tmpl→<pkg>/web/idempotency/IdempotencyKeyFilter.java
The filter logic:
- Only guards
POSTrequests that carry anIdempotency-Keyheader; everything else passes straight through. - Computes a fingerprint = hash of method + URI + body.
store.find(key):- hit, same fingerprint → replay the stored status/body, skip the handler.
- hit, different fingerprint →
422(the key was reused for a different request). - miss → run the handler, then
store.save(key, response).
Step 3 — Implement the store
Generate (or point the user to write) one IdempotencyStore implementation:
@Component
class RedisIdempotencyStore implements IdempotencyStore {
// SET key <json> NX EX <ttl>; GET key. Use a short TTL (minutes–hours), not forever.
// A DB variant: unique column on key + an inserted-at for expiry.
}
Register the filter (e.g. a FilterRegistrationBean<IdempotencyKeyFilter>) scoped to
the POST routes that need it — not every endpoint.
Step 4 — Report
Created:
src/main/java/.../web/idempotency/IdempotencyStore.java (SPI)
src/main/java/.../web/idempotency/IdempotencyKeyFilter.java (filter)
+ a store implementation (Redis/DB) — implement before shipping
Failure modes — do NOT
- Do NOT store responses forever — set a TTL; an unbounded store is a memory/disk leak.
- Do NOT replay on a different request body under the same key — return 422 instead.
- Do NOT apply idempotency to safe methods (GET/HEAD) — they are already idempotent.
- Do NOT key only on the header — include a request fingerprint so a reused key can't replay an unrelated response.
- Do NOT store the key without scoping it to the caller/tenant if keys aren't globally unique in your system.
Integration Test — Scaffold (Testcontainers)
Generates an integration test that boots the real Spring context against a real database in a container — so it catches dialect, constraint, and migration bugs that H2 or mocks silently hide.
Step 1 — Detect conventions (do not assume)
Read before generating:
- Existing test setup: look for a base test class, an
@AutoConfigureTestDatabase, or existing@Testcontainersusage; extend the existing base instead of adding a rival. - Dependencies: confirm
org.springframework.boot:spring-boot-testcontainers,org.testcontainers:junit-jupiter, andorg.testcontainers:postgresqlare present; if not, list them for the user'spom.xml/build.gradle. - Spring Boot version:
@ServiceConnectionneeds 3.1+. On older versions fall back to@DynamicPropertySource(and say so). - Test naming/runner:
*ITruns under Failsafe / a GradleintegrationTesttask;*Testruns under Surefire. Match the project's split.
Step 2 — Render templates
From assets/, substitute {{PACKAGE}} and {{ENTITY}}:
AbstractIntegrationTest.java.tmpl→<pkg>/AbstractIntegrationTest.java— the base:@SpringBootTest+@Testcontainers, astatic @Container @ServiceConnectionPostgreSQLContainer<>("postgres:16")(started once, shared by subclasses).ExampleIT.java.tmpl→<pkg>/{{ENTITY}}IT.java— extends the base, autowires the real repository, and shows an Awaitility-polled async assertion.
Step 3 — Why these choices
- Real Postgres over H2/mocks: integration tests should fail when the real database would fail. H2 accepts SQL Postgres rejects (and vice versa); mocks prove nothing about persistence.
@ServiceConnectionover@DynamicPropertySource: the container's URL/credentials flow into the context automatically — less boilerplate, fewer wiring mistakes.- Awaitility over
Thread.sleep: poll until the condition holds (or times out) instead of sleeping a fixed guess.Thread.sleepin tests is flaky and slow — it trips thetest-thread-sleepguardrail.
Step 4 — Report
Created:
src/test/java/.../AbstractIntegrationTest.java (@SpringBootTest + Testcontainers Postgres)
src/test/java/.../<Entity>IT.java (real repository + Awaitility async assert)
Note any missing Testcontainers dependencies the user must add.
Failure modes — do NOT
- Do NOT swap in H2 or
@DataJpaTestembedded DB for a test meant to exercise real infra. - Do NOT use
Thread.sleepfor async waits — use Awaitility (test-thread-sleep). - Do NOT create a non-static container per test method (slow; loses the shared-startup win).
- Do NOT hand-wire the datasource when
@ServiceConnectionis available. - Do NOT name a Testcontainers boot test
*Testif the project runs only*ITunder Failsafe.
JPA Entity — Scaffold
Generate an entity that is born compliant with ruleset.json. The point: if the
code is correct from the start, jpa-optimistic-lock, jpa-entity-equals, and
friends never need to fire.
Step 1 — Detect project conventions (do not assume)
Read before generating:
- Base class / auditing: look for a
@MappedSuperclass(e.g.BaseEntity,AuditableEntity) andAuditingEntityListener/@EnableJpaAuditing. If present, extend it instead of re-declaring id/audit fields. - Id strategy: match the codebase —
GenerationType.IDENTITY(Postgres/MySQL serial) vs assigned UUID. DefaultIDENTITYfor numeric, or UUID if entities use it. - Package + path: mirror an existing entity's package (e.g.
….domain/….model/….entity). Write to the matchingsrc/main/java/...path. - Lombok: if the project uses Lombok, use
@Getter/@Setter; otherwise write explicit accessors. - Soft-delete: if other entities use a
deleted/deletedAtcolumn or@SQLDelete, offer the same; otherwise skip.
Step 2 — Generate (the non-negotiable invariants)
Every generated entity MUST have:
@Versionfield for optimistic locking.equals/hashCodebased on a stable business key or an assigned UUID — never the generated@Id(null pre-persist, breaks Set/Map membership).- Audit fields via the project's base class, or
@CreatedDate/@LastModifiedDateif auditing is enabled and there's no base class. - Jakarta imports (
jakarta.persistence.*), Spring Boot 3.x.
Use assets/jpa-entity.java.tmpl as the shape; fill {{PACKAGE}}, {{ENTITY}},
{{TABLE}}, {{FIELDS}}, {{ID_STRATEGY}}. The template carries a uid UUID
business key (used by equals/hashCode) and @CreatedDate/@LastModifiedDate audit
fields. If extending a base class, drop the id/version/audit fields it already
provides (but ensure @Version exists somewhere in the hierarchy — if the base lacks
it, keep it on the entity).
Step 3 — Repository + migration
- Generate a
Repository extends JpaRepository<Entity, IdType>next to it. - If the entity has associations (
@ManyToOne/@OneToMany/@OneToOne), keep them LAZY and add a fetch-aware finder usingassets/repository-entitygraph.java.tmpl— an@EntityGraph(attributePaths = {"…"})override or ajoin fetch@Query. Reads then load the graph explicitly, sojpa-eager-fetch/nplus1-heuristicnever fire. - If the project uses Flyway/Liquibase, invoke the
db-migrationskill to emit the matchingCREATE TABLEmigration in the same change — entity and schema stay in lockstep. Do NOT rely onddl-auto: update.
Step 4 — Report
List created files and confirm the invariants:
Created:
src/main/java/.../<Entity>.java (@Version ✓, business-key equals/hashCode ✓, audit ✓)
src/main/java/.../<Entity>Repository.java
src/main/resources/db/migration/V<n>__create_<table>.sql (if Flyway)
Failure modes — do NOT
- Do NOT emit an entity without
@Version(the whole reason this skill exists). - Do NOT base equals/hashCode on the generated
@Id. - Do NOT duplicate id/audit fields already provided by a detected base class.
- Do NOT invent a package — mirror an existing entity, or ask if none exists.
- Do NOT use
javax.persistence(that's Spring Boot 2.x); usejakarta.persistence. - Do NOT skip the migration when the project clearly uses Flyway/Liquibase.
JWT Auth — Scaffold
Bearer-token auth for a stateless API. The cardinal rule: never read claims from a token you have not verified. Prefer the framework path; the custom filter is a fallback, not the default.
Step 1 — Detect conventions
- Confirm a
SecurityFilterChainexists (use thesecurity-filter-chainskill first); JWT auth plugs into it withSessionCreationPolicy.STATELESSand CSRF disabled. - Check for an issuer/JWKS endpoint (Auth0/Keycloak/Cognito) → strongly favors Option 1.
- Confirm the signing secret/JWKS URI is in config/env, never in source.
Step 2 — Option 1 (RECOMMENDED): Spring Security resource server
Let Spring validate the token — signature, exp, nbf, issuer — no hand-rolled crypto:
// build.gradle: implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
http.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
@Bean // JWKS (asymmetric) — the usual case with an external IdP:
JwtDecoder jwtDecoder(@Value("${security.jwt.jwks-uri}") String jwksUri) {
return NimbusJwtDecoder.withJwkSetUri(jwksUri).build();
}
// HMAC (shared secret) variant:
// NimbusJwtDecoder.withSecretKey(new SecretKeySpec(secret.getBytes(UTF_8), "HmacSHA256"))
// .macAlgorithm(MacAlgorithm.HS256).build();
Map scopes/roles with a JwtAuthenticationConverter if needed. Choose this whenever an
IdP issues the tokens — you maintain zero verification code.
Step 3 — Option 2 (only if you must): custom filter
For teams that issue their own tokens and can't add the resource server. Render from
assets/, substitute {{PACKAGE}}:
JwtService.java.tmpl→<pkg>/security/JwtService.java(issue + verify via jjwt)JwtAuthenticationFilter.java.tmpl→<pkg>/security/JwtAuthenticationFilter.javaJwtAuthenticationEntryPoint.java.tmpl→<pkg>/security/JwtAuthenticationEntryPoint.java
Requires jjwt: io.jsonwebtoken:jjwt-api + runtime jjwt-impl, jjwt-jackson.
What the templates guarantee:
Jwts.parser().verifyWith(key).build().parseSignedClaims(token)— verifies the signature, rejectsalg=noneand algorithm-confusion, and enforcesexp/nbf.- The filter only trusts a token after
verifyreturns; on anyJwtExceptionit clears the context and returns 401 JSON via the entry point — never partially authenticated. - The secret is injected from
${security.jwt.secret}(env), HS256 key >= 256 bits. - Authorities are mapped from a
rolesclaim (fallbackROLE_USER) in the filter'sauthorities(...)helper — adjust the claim name/prefix to match your issuer sohasRole(...)/@PreAuthorizereflect real token roles.
Wire the filter in SecurityConfig:
http.exceptionHandling(e -> e.authenticationEntryPoint(jwtAuthenticationEntryPoint))
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
Step 4 — Report
List created files and state which option was used. For Option 2, confirm: signature
verified, alg=none rejected, exp checked, secret from env, 401 JSON on failure.
Failure modes — do NOT
- Do NOT read claims from an unverified token, and do NOT call a "parse without verify" API.
- Do NOT accept
alg=noneor let the token's header pick the algorithm (algorithm confusion). - Do NOT hardcode the signing secret — inject from env/config (
sec-hardcoded-secret). - Do NOT skip the
expcheck or set tokens that never expire. - Do NOT hand-roll Base64 + HMAC parsing — use the resource server or a vetted library (jjwt).
- Do NOT return 200/HTML on auth failure — return 401 JSON for an API.
REST Error Handler — Scaffold
One advice class so every endpoint shares one error shape. Clients always get an
RFC 7807 ProblemDetail (application/problem+json), and the server never leaks a
stack trace or internal message on an unexpected failure.
Step 1 — Detect conventions (do not assume)
Read before generating:
- Existing advice: search for
@RestControllerAdvice/@ControllerAdviceor a class extendingResponseEntityExceptionHandler. If one exists, ADD the missing handlers to it (show a diff) rather than creating a competing advice — two global advices fighting over the same exception is non-deterministic. - Base package: mirror where existing
*Controller.javalive; place the advice in the….webpackage alongside them. - Existing not-found exception: if the project already has a
NotFoundException/ResourceNotFoundException, reuse it; don't generate a duplicate. - Error type base URI: pick a stable base for the
typefield (e.g.https://<app>/problems); fill{{PROBLEM_BASE}}.
Step 2 — Render templates
From assets/, substitute {{PACKAGE}} and {{PROBLEM_BASE}}:
GlobalExceptionHandler.java.tmpl→<pkg>/web/GlobalExceptionHandler.javaNotFoundException.java.tmpl→<pkg>/NotFoundException.java(skip if one exists)
The advice maps three cases:
MethodArgumentNotValidException→ 400, body carries anerrorsmap offield → messagebuilt fromgetBindingResult().getFieldErrors().NotFoundException→ 404 with the domain message.Exception(fallback) → 500, logged server-side, body is an opaque"Unexpected error"— noex.getMessage(), no stack trace.
Step 3 — Wire it up
- Throw
NotFoundExceptionfrom services (e.g. onfindById(...).orElseThrow(...)), never returnnullto the controller. - Spring 6 serializes
ProblemDetailasapplication/problem+jsonautomatically; no extra config needed. Confirm the app is Spring Boot 3.x (Spring 6) —ProblemDetaildoes not exist in Spring 5 / Boot 2.x.
Step 4 — Report
List created files and confirm the contract:
Created:
src/main/java/.../web/GlobalExceptionHandler.java (400 validation, 404, 500 fallback)
src/main/java/.../NotFoundException.java (if absent)
Failure modes — do NOT
- Do NOT return
ex.getMessage()or a stack trace in the fallback 500 (information leak). - Do NOT create a second global advice if one already exists — extend it.
- Do NOT use
javax.*or Spring 5@ExceptionHandlerreturning a hand-rolled body; use Spring 6ProblemDetail(jakarta.*imports). - Do NOT catch and swallow — every handled exception still produces a response.
- Do NOT map a generic
Exceptionto anything other than 500.
Security Filter Chain — Scaffold
Generates a SecurityConfig whose authorization is deny-by-default, so a new
endpoint is locked until you explicitly open it — the opposite of the permit-all
defaults that trip sec-missing-method-auth. See references/security.md for the why.
Step 1 — Detect conventions (do not assume)
Read before generating:
- Existing security config: search for a
@Bean SecurityFilterChainor the legacyWebSecurityConfigurerAdapter. If one exists, EDIT it (show a diff) — two filter chains with overlapping matchers is non-deterministic. If it's the deprecated adapter, offer to migrate it to the component-basedSecurityFilterChainbean. - Auth model — pick before generating:
- Cookie/session (server renders, browser holds a session cookie) → KEEP CSRF,
allow the default
SessionCreationPolicy. - Stateless token (JWT/opaque bearer, no cookie) →
SessionCreationPolicy.STATELESSand CSRF disabled (no cookie to forge). Pair with thejwt-authskill.
- Cookie/session (server renders, browser holds a session cookie) → KEEP CSRF,
allow the default
- Origins: find the SPA/mobile origins for CORS; never reflect
*with credentials. - Base package: mirror existing
config/securitypackages.
Step 2 — Render the template
From assets/SecurityConfig.java.tmpl, substitute {{PACKAGE}} and {{ALLOWED_ORIGIN}}
→ <pkg>/config/SecurityConfig.java. It provides three beans:
SecurityFilterChain—authorizeHttpRequestsending inanyRequest().authenticated()(deny-by-default); only health/auth endpoints arepermitAll().PasswordEncoder→BCryptPasswordEncoder(adaptive; never MD5/SHA-1/plaintext —sec-weak-hash).CorsConfigurationSource— explicit origins/methods/headers,allowCredentials(true)only with exact origins.
Step 3 — Tune for the chosen auth model
- Cookie/session: delete the
.csrf(...).disable()and.sessionManagement(...)lines. CSRF protection stays ON. Add aformLogin/httpBasicor your login flow. - Stateless token: keep both lines; register the bearer filter from
jwt-authbeforeUsernamePasswordAuthenticationFilter. - Prefer
requestMatchers(HttpMethod.X, "...")over broad patterns; keep the matcher list ordered most-specific first.
Step 4 — Report
Created:
src/main/java/.../config/SecurityConfig.java
(deny-by-default authz ✓, BCrypt ✓, CORS ✓, CSRF: <kept|disabled> for <session|token>)
State which auth model was chosen and why CSRF is on/off.
Failure modes — do NOT
- Do NOT leave a wildcard
anyRequest().permitAll()— that defeats the whole config. - Do NOT disable CSRF for cookie/session auth (CSRF is exactly that threat model).
- Do NOT set
allowedOrigins("*")together withallowCredentials(true)(forbidden combo). - Do NOT store passwords with MD5/SHA-1/SHA-256 or plaintext — use BCrypt/Argon2 (
sec-weak-hash). - Do NOT use the deprecated
WebSecurityConfigurerAdapter/.and()chaining (Spring Security 6). - Do NOT add a second SecurityFilterChain bean that overlaps an existing one.
Spring Boot Toolkit — Setup
Installs the enforcement layer into the project's .claude/ so it is committed
and shared with the whole team — a teammate who clones the repo gets the guardrails
even without installing this plugin. The authoring skills (jpa-entity,
spring-rest-endpoint, db-migration) stay plugin-provided and are not copied.
Plugin source root (where templates live): the directory containing this skill's
parent, i.e. plugins/java-backend-toolkit/. Resolve files relative to it.
Step 1 — Verify this is a Spring Boot + JPA project
Confirm at least one of:
pom.xmlcontainingspring-boot-starter, orbuild.gradle/build.gradle.ktscontainingspring-boot.
And JPA in use: spring-boot-starter-data-jpa (or jakarta.persistence / javax.persistence imports).
If not a Spring Boot + JPA project → stop and say so. This toolkit's v1 paved road is Spring Boot 3.x + Spring Data JPA only (no Kotlin, reactive, or non-Spring).
Step 2 — Detect project slots (smart defaults, confirm — do not interrogate)
Scan, propose, ask only to confirm:
| Slot | Detect from | Default if absent |
|---|---|---|
MIGRATION_TOOL | flyway-core dep or src/main/resources/db/migration/ → Flyway; liquibase-core → Liquibase | Flyway |
BASE_ENTITY | a @MappedSuperclass class and/or AuditingEntityListener usage | a @MappedSuperclass BaseEntity with Spring Data JPA auditing |
PROJECT_NAME | CLAUDE.md identity / repo dir name | repo directory name |
| strict mode | --strict arg | jpql-injection blocks (already the default in guardrails-config.json) |
Show the resolved slot values in one block and get a single confirmation.
Step 3 — Install the guardrail hook (copy flat into .claude/hooks/)
Copy these three files from the plugin's hooks/ and rules/ into the project's
.claude/hooks/ (flat — the hook finds its ruleset beside itself):
hooks/jpa-guardrail.py→.claude/hooks/jpa-guardrail.pyrules/ruleset.json→.claude/hooks/ruleset.jsonhooks/guardrails-config.json→.claude/hooks/guardrails-config.json
If --strict was NOT passed and the user wanted advisory-only for injection too,
edit the copied guardrails-config.json to set "strictChecks": []. Otherwise leave
the default (["jpql-injection"]).
Do not modify the plugin's source files — only the copies in the project.
Step 4 — Register the hook in .claude/settings.json (merge, never clobber)
Read .claude/settings.json (create {} if absent). Under hooks.PostToolUse,
add this entry only if an equivalent is not already present:
{ "matcher": "Write|Edit", "hooks": [{ "type": "command", "command": "python3 .claude/hooks/jpa-guardrail.py" }] }
Preserve every existing hook (e.g. protect-files.py, observe.py). Append; do not
replace the array. If a jpa-guardrail.py entry already exists, skip (idempotent).
Step 5 — Inject the Spring Boot rule block into CLAUDE.md
Load assets/rules/springboot-rules.md.tmpl, substitute {{PROJECT_NAME}},
{{BASE_ENTITY}}, {{MIGRATION_TOOL}}, {{TEMPLATE_VERSION}} (= toolkit version).
- If the project keeps rules in
.claude/rules/, write.claude/rules/springboot.md. - Otherwise append a
## Spring Boot conventionssection toCLAUDE.md(do not duplicate if a prior install already added it — replace that section instead).
Step 6 — Install the reviewer agent (unless --no-agent)
Copy agents/springboot-reviewer.md → .claude/agents/springboot-reviewer.md.
This makes the reviewer available to teammates and keeps its checklist (the same
ruleset.json) in the repo.
Step 7 — Report
Print a summary:
Installed Spring Boot guardrails:
.claude/hooks/jpa-guardrail.py (PostToolUse: Write|Edit on *.java)
.claude/hooks/ruleset.json (6 rules — 5 hook-enforced, 1 reviewer-only)
.claude/hooks/guardrails-config.json (strict: <strictChecks>)
.claude/agents/springboot-reviewer.md
CLAUDE.md (Spring Boot conventions block)
Try it: create an @Entity without @Version → the hook reminds you at write time.
Authoring helpers (from the plugin): jpa-entity, spring-rest-endpoint, db-migration.
Tune checks in guardrails-config.json (disabledChecks / strictChecks); suppress per-file
with `// jbt:ignore <rule-id>`.
Failure modes — do NOT
- Do NOT clobber existing hooks in settings.json — merge only.
- Do NOT copy the scaffold skills into the project — they are plugin-provided.
- Do NOT edit the plugin's source
ruleset.json/guardrails-config.json; only project copies. - Do NOT install on a non-Spring-Boot or Kotlin/reactive project — stop with a clear message.
- Do NOT invent slot values you did not detect or confirm.
- Do NOT register the hook twice — check for an existing entry first.
Spring REST Endpoint — Scaffold
Generates a controller that returns DTOs only, so the entity-in-controller
guardrail never fires. Output: controller, response DTO, request DTO, a service
method, and an entity→DTO mapper.
Step 1 — Detect conventions
- Base package: infer from
src/main/java/.../(the deepest package holding existing*Controller.java, else the application's root package). - Existing patterns: if the project already has a
mapper/dtopackage or MapStruct on the classpath, match it; otherwise generate a plain hand-written mapper.
Step 2 — Gather the resource
Ask (or take from argument): resource name (e.g. Order), and which operations
(GET /{id}, GET list, POST, PUT, DELETE). Default to read + create if unspecified.
Step 3 — Render templates
From assets/, substitute {{PACKAGE}}, {{RESOURCE}}, {{RESOURCE_LOWER}}:
Controller.java.tmpl→<pkg>/web/{{RESOURCE}}Controller.javaResponseDto.java.tmpl→<pkg>/web/dto/{{RESOURCE}}Response.javaRequestDto.java.tmpl→<pkg>/web/dto/{{RESOURCE}}Request.java
Rules baked into the templates:
- Controller methods return
{{RESOURCE}}Response/List<{{RESOURCE}}Response>/ResponseEntity<{{RESOURCE}}Response>— never the entity. @PostMapping/@PutMappingtake@Valid @RequestBody {{RESOURCE}}Request.- A
{{RESOURCE}}Mapper(or inline mapping in the service) converts entity → response.
Step 4 — Wire the service
If a {{RESOURCE}}Service exists, add the method; otherwise generate a minimal
service that depends on the repository and returns the mapped DTO. Keep the
@Transactional boundary on the public service method (not the controller).
Variant — Cursor (keyset) pagination
For list endpoints that page large or frequently-written tables, prefer cursor
pagination over OFFSET/Pageable. Offset re-scans and skips the leading rows
(slower as the page number grows) and skips or duplicates rows when concurrent
inserts/deletes shift the offset between requests. Keyset paging is stable because
it pages by the last seen key, not a row count.
Render assets/CursorPage.java.tmpl → <pkg>/web/dto/CursorPage.java, then
expose GET /api/{{RESOURCE_LOWER}}s?cursor=&size= returning CursorPage<{{RESOURCE}}Response>:
// Repository — page by the last seen id (keyset), not OFFSET.
@Query("select e from {{RESOURCE}} e where e.id > :cursor order by e.id")
List<{{RESOURCE}}> findAfter(@Param("cursor") long cursor, Pageable limit);
// Service — fetch size+1 is optional; here nextCursor = last id, or null when short.
List<{{RESOURCE}}> rows = repo.findAfter(cursor, PageRequest.of(0, size));
String next = rows.size() < size ? null : String.valueOf(rows.get(rows.size() - 1).getId());
return new CursorPage<>(map(rows), next);
The client passes cursor=0 (or omits it) for the first page and echoes nextCursor
until it comes back null. Use the table's primary key (or any monotonic, indexed
column) as the cursor so the where … > :cursor scan stays index-backed.
Step 5 — Report
List created files and remind: the controller never returns the entity; map in the
service/mapper. If the resource has no entity yet, suggest /jpa-entity first.
Failure modes — do NOT
- Do NOT return, accept, or expose a JPA
@Entityin any controller signature. - Do NOT put
@Transactionalon the controller. - Do NOT skip
@Validon request bodies. - Do NOT overwrite an existing controller without showing a diff and confirming.
Spring Boot Conventions
The rules enforced by the guardrail hook (ruleset.json) and the always-on summary
in CLAUDE.md are deliberately terse. This skill holds the rationale and the fix
patterns, split by domain so you only load what's relevant.
Load the reference for the layer you're in:
| You're working on… | Read | Covers rules |
|---|---|---|
| Entities, repositories, queries | references/persistence.md | jpa-optimistic-lock, jpa-entity-equals, nplus1-heuristic, jpql-injection |
| Controllers, request/response | references/web.md | entity-in-controller |
Service methods, @Transactional | references/transactions.md | tx-proxy |
| Tests | references/testing.md | (slice tests, Testcontainers) |
Each reference explains: the failure mode, why it bites, the correct pattern, and how
to suppress the guardrail (// jbt:ignore <rule-id>) when a deviation is intentional.
This is reference material, not a tutorial — it assumes you know Spring Boot and focuses on the mistakes that are easy to miss.
Test Slice — Scaffold
A slice test loads only the beans for one layer, so it's fast and its failure points
straight at that layer. Use the narrowest slice that still proves the behavior; only
escalate to @SpringBootTest when the test genuinely spans layers (then see the
integration-test skill for the Testcontainers full-stack case).
Step 1 — Pick the slice
@DataJpaTest— repositories, entity mappings, custom queries. Loads JPA only, each test runs in a transaction rolled back at the end. Embedded DB by default; point it at real Postgres with@AutoConfigureTestDatabase(replace = NONE)+ Testcontainers.@WebMvcTest(XController.class)— controller routing, JSON, validation, status codes, error mapping. Loads the MVC layer only; the service is a mock.- Full
@SpringBootTest— only when the behavior crosses controller → service → repository in one flow. Heavier; don't default to it.
Step 2 — Detect conventions
- Test framework: JUnit 5 + AssertJ assumed; match Mockito/Hamcrest if the project differs.
- Mock annotation by version:
@MockitoBean(Spring Boot 3.4+) vs@MockBean(≤ 3.3, deprecated in 3.4). Check the Boot version and use the right one. - Mirror the existing
src/test/javapackage layout and naming (*Testunder Surefire).
Step 3 — Render templates
From assets/, substitute {{PACKAGE}}, {{ENTITY}}, {{ENTITY_LOWER}}:
DataJpaTest.java.tmpl→<pkg>/{{ENTITY}}RepositoryTest.java— autowires the repository +TestEntityManager, asserts with AssertJ.WebMvcTest.java.tmpl→<pkg>/{{ENTITY}}ControllerTest.java—MockMvcdrives the controller,@MockitoBean {{ENTITY}}Servicestubs the dependency,jsonPathchecks the body.
Step 4 — Report
Created:
src/test/java/.../<Entity>RepositoryTest.java (@DataJpaTest, rolls back per test)
src/test/java/.../<Entity>ControllerTest.java (@WebMvcTest, MockMvc + mocked service)
State which slice(s) you generated and which mock annotation matches the Boot version.
Failure modes — do NOT
- Do NOT reach for
@SpringBootTestwhen a slice proves the behavior — it's slower and broader. - Do NOT load the database in a
@WebMvcTest— mock the service; the web slice has no repo. - Do NOT mix
@MockBeanand@MockitoBeanarbitrarily — pick the one for your Boot version. - Do NOT assume
@DataJpaTest's embedded DB matches production SQL — use Testcontainers when dialect fidelity matters (seeintegration-test). - Do NOT forget the controller class argument:
@WebMvcTest({{ENTITY}}Controller.class)keeps the slice narrow; a bare@WebMvcTestloads every controller.
Agents 1
You are a senior Spring Boot reviewer. Your checklist is the toolkit's single
source of truth: ruleset.json (installed at .claude/hooks/ruleset.json, or in
the plugin at rules/ruleset.json). Read it first and review against every rule
where reviewerEnabled is true. Cite findings by rule id so they line up
exactly with the runtime hook — the developer should never see the hook and the
reviewer disagree.
How to run a review
- Read
ruleset.jsonto load the current rules (do not hardcode them — they evolve). - Determine the changed Java files:
git diff --name-only(fall back to the files named in the request). - For each rule, scan the relevant files. Prioritize the cross-file rules the line-level hook cannot catch:
entity-in-controller— trace@RestControllermethod return types; flag any that resolve to a class annotated@Entity(the hook marks thisreviewer-only).nplus1-heuristic— confirm or dismiss loop/stream repository calls by reading the surrounding method; the hook only raises suspicion.
- Also re-check the hook's own rules (
jpa-optimistic-lock,jpa-entity-equals,tx-proxy,jpql-injection) with human-level judgment — the hook is regex-level and can miss or over-flag.
Output format
Group findings by severity (critical → warning → info), each as:
[<rule-id>] <file>:<line> — <one-line problem>
Why: <concrete consequence in this code>
Fix: <the specific change>
End with a one-line verdict: APPROVE (no critical/warning), APPROVE WITH NITS
(info only), or CHANGES REQUESTED (≥1 critical/warning).
Boundaries
- Review only; never edit files. Report findings, let the developer apply them.
- Stay within the ruleset's scope (Spring Boot 3.x + JPA). Do not invent rules
not in
ruleset.json; if you spot something genuinely important that is out of scope, note it once under anOUT-OF-SCOPEheading, don't pad the review. - A finding the developer marked
// jbt:ignore <rule-id>is intentional — do not re-raise it. - Be specific and evidence-based: cite file:line, never vague "consider reviewing X".
Sponsors
Details
- Marketplace
- ShipWithAI/shipwithai-plugins
- Source
- plugins/java-backend-toolkit
- Author
- ShipWithAI
- Category
- Productivity