Back to Backend Development

spring-boot-crud-patterns

Spring BootCRUDREST APISpring Data JPAJavaBackendArchitectureDTOs
282📄 MIT🕒 2026-06-15Source ↗

Install this skill

npx skills add giuseppe-trisciuoglio/developer-kit

Works across Claude Code, Cursor, Codex, Copilot & Antigravity

This skill provides a standardized architectural framework for building CRUD operations in Spring Boot 3.5+ applications. It promotes a strictly layered approach that separates domain logic from infrastructure details, ensuring that JPA-specific code does not leak into business rules. By enforcing a feature-driven folder structure, the approach isolates domain aggregates, application services, and REST presentation layers. This separation improves maintainability, allowing developers to manage persistence through Repository interfaces while keeping the core domain pure. The pattern relies on Java records for DTOs and constructor-based injection for dependency management, ensuring that services remain testable and modular. Adhering to these conventions results in predictable codebases where business logic remains shielded from framework changes, simplifying long-term refactoring and integration with complex persistence requirements.

When to Use This Skill

  • Building feature-aligned microservices following Domain-Driven Design principles
  • Migrating legacy Spring controllers toward a clean layered architecture
  • Standardizing CRUD endpoint creation across multi-module Spring Boot projects
  • Implementing strict persistence boundaries between business logic and database tables

How to Invoke This Skill

Example prompts that trigger this skill in Claude Code, Cursor, or Antigravity:

  • implement Spring CRUD controller
  • refine feature-based repository
  • map DTOs for JPA aggregate
  • add pagination to REST list endpoint
  • setup domain-driven CRUD structure

Pro Tips

  • 💡**Automate DTO Mapping:** Utilize libraries like MapStruct to automatically map between JPA entities and DTOs, significantly reducing manual mapping boilerplate and potential errors.
  • 💡**Leverage Spring's Validation API:** Combine `@Valid` and JSR 380 annotations (like `@NotNull`, `@Size`) on DTOs to ensure robust input validation at the controller layer before data reaches your service logic.
  • 💡**Strategic Transactional Boundaries:** Ensure your `@Transactional` annotations are placed correctly, typically at the service layer, to define clear transaction boundaries and maintain data integrity across multiple repository operations.

What this skill does

  • Structures code into distinct domain, application, and infrastructure feature packages
  • Maps domain aggregates to JPA entities using explicit conversion layers
  • Implements RESTful endpoints using immutable Java records for request/response payloads
  • Enforces transactional boundaries using Spring's @Transactional on service methods
  • Provides pagination-ready repository interfaces using Spring Data JPA

When not to use it

  • Simple prototypes or small scripts that do not require architectural separation
  • Applications where the overhead of mapping between domain models and JPA entities is considered excessive

Example workflow

  1. Organize project directories into feature-specific folders for domain and application logic
  2. Create domain aggregates and value objects that remain independent of JPA annotations
  3. Define repository interfaces in the domain layer to handle data access contracts
  4. Implement infrastructure adapters that map domain entities to Spring Data JPA entities
  5. Develop application services to orchestrate transactions and object mapping
  6. Expose endpoints through feature-specific controllers using DTO records

Prerequisites

  • Java 17 or higher
  • Spring Boot 3.5.x or later
  • Spring Data JPA and Web starters

Pitfalls & limitations

  • !Over-engineering simple CRUD operations where direct entity exposure might suffice
  • !Tight coupling occurring if developers fail to maintain the mapping layer between domain and infrastructure
  • !Neglecting proper transaction management on service-layer methods

FAQ

Should I use @Entity in my domain layer?
No, keep your domain layer framework-free. Use the infrastructure layer to map domain objects to JPA-annotated entities.
What is the recommended way to pass data to the presentation layer?
Use immutable Java records as DTOs. Map your domain objects to these records at the service boundary.
How do I handle database transactions?
Annotate your application service methods with @Transactional to ensure that business operations maintain data integrity.
Is this approach suitable for reactive Spring applications?
This pattern specifically focuses on blocking JPA operations. For reactive stacks, you would need to adjust the repository contracts accordingly.

How it compares

Unlike manual boilerplate generation, this pattern forces a disciplined separation of concerns that prevents domain logic from leaking into infrastructure code.

Source & trust

282 stars📄 MIT🕒 Updated 2026-06-15
📄 Full skill instructions — original source: giuseppe-trisciuoglio/developer-kit
# Spring Boot CRUD Patterns

## Overview

Deliver feature-aligned CRUD services that separate domain, application, presentation, and infrastructure layers while preserving Spring Boot 3.5+ conventions. This skill distills the essential workflow and defers detailed code listings to reference files for progressive disclosure.

## When to Use

- Implement REST endpoints for create/read/update/delete workflows backed by Spring Data JPA.
- Refine feature packages following DDD-inspired architecture with aggregates, repositories, and application services.
- Introduce DTO records, request validation, and controller mappings for external clients.
- Diagnose CRUD regressions, repository contracts, or transaction boundaries in existing Spring Boot services.
- Trigger phrases: **"implement Spring CRUD controller"**, **"refine feature-based repository"**, **"map DTOs for JPA aggregate"**, **"add pagination to REST list endpoint"**.

## Prerequisites

- Java 17+ project using Spring Boot 3.5.x (or later) with spring-boot-starter-web and spring-boot-starter-data-jpa.
- Constructor injection enabled (Lombok @RequiredArgsConstructor or explicit constructors).
- Access to a relational database (Testcontainers recommended for integration tests).
- Familiarity with validation (jakarta.validation) and error handling (ResponseStatusException).

## Quickstart Workflow

1. **Establish Feature Structure**
Create feature/<name>/ directories for domain, application, presentation, and infrastructure.
2. **Model the Aggregate**
Define domain entities and value objects without Spring dependencies; capture invariants in methods such as create and update.
3. **Expose Domain Ports**
Declare repository interfaces in domain/repository describing persistence contracts.
4. **Provide Infrastructure Adapter**
Implement Spring Data adapters in infrastructure/persistence that map domain models to JPA entities and delegate to JpaRepository.
5. **Implement Application Services**
Create transactional use cases under application/service that orchestrate aggregates, repositories, and mapping logic.
6. **Publish REST Controllers**
Map DTO records under presentation/rest, expose endpoints with proper status codes, and wire validation annotations.
7. **Validate with Tests**
Run unit tests for domain logic and repository/service tests with Testcontainers for persistence verification.

Consult references/examples-product-feature.md for complete code listings that align with each step.

## Implementation Patterns

### Domain Layer

- Define immutable aggregates with factory methods (Product.create) to centralize invariants.
- Use value objects (Money, Stock) to enforce type safety and encapsulate validation.
- Keep domain objects framework-free; avoid @Entity annotations in the domain package when using adapters.

### Application Layer

- Wrap use cases in @Service classes using constructor injection and @Transactional.
- Map requests to domain operations and persist through domain repositories.
- Return response DTOs or records produced by dedicated mappers to decouple domain from transport.

### Infrastructure Layer

- Implement adapters that translate between domain aggregates and JPA entities; prefer MapStruct or manual mappers for clarity.
- Configure repositories with Spring Data interfaces (e.g., JpaRepository<ProductEntity, String>) and custom queries for pagination or batch updates.
- Externalize persistence properties (naming strategies, DDL mode) via application.yml; see references/spring-official-docs.md.

### Presentation Layer

- Structure controllers by feature (ProductController) and expose REST paths (/api/products).
- Return ResponseEntity with appropriate codes: 201 Created on POST, 200 OK on GET/PUT/PATCH, 204 No Content on DELETE.
- Apply @Valid on request DTOs and handle errors with @ControllerAdvice or ResponseStatusException.

## Validation and Observability

- Write unit tests that assert domain invariants and repository contracts; refer to references/examples-product-feature.md integration test snippets.
- Use @DataJpaTest and Testcontainers to validate persistence mapping, pagination, and batch operations.
- Surface health and metrics through Spring Boot Actuator; monitor CRUD throughput and error rates.
- Log key actions at info for lifecycle events (create, update, delete) and use structured logging for audit trails.

## Best Practices

- Favor feature modules with clear boundaries; colocate domain, application, and presentation code per aggregate.
- Keep DTOs immutable via Java records; convert domain types at the service boundary.
- Guard write operations with transactions and optimistic locking where concurrency matters.
- Normalize pagination defaults (page, size, sort) and document query parameters.
- Capture links between commands and events where integration with messaging or auditing is required.

## Constraints and Warnings

- Avoid exposing JPA entities directly in controllers to prevent lazy-loading leaks and serialization issues.
- Do not mix field injection with constructor injection; maintain immutability for easier testing.
- Refrain from embedding business logic in controllers or repository adapters; keep it in domain/application layers.
- Validate input aggressively to prevent constraint violations and produce consistent error payloads.
- Ensure migrations (Liquibase/Flyway) mirror aggregate evolution before deploying schema changes.

## References

- [HTTP method matrix, annotation catalog, DTO patterns.](references/crud-reference.md)
- [Progressive examples from starter to advanced feature implementation.](references/examples-product-feature.md)
- [Excerpts from official Spring guides and Spring Boot reference documentation.](references/spring-official-docs.md)
- [Python generator to scaffold CRUD boilerplate from entity spec.](scripts/generate_crud_boilerplate.py) Usage: python skills/spring-boot/spring-boot-crud-patterns/scripts/generate_crud_boilerplate.py --spec entity.json --package com.example.product --output ./generated
- Templates required: place .tpl files in skills/spring-boot/spring-boot-crud-patterns/templates/ or pass --templates-dir <path>; no fallback to built-ins. See templates/README.md.
- Usage guide: [references/generator-usage.md](references/generator-usage.md)
- Example spec: skills/spring-boot/spring-boot-crud-patterns/assets/specs/product.json
- Example with relationships: skills/spring-boot/spring-boot-crud-patterns/assets/specs/product_with_rel.json

How to Use This Skill Unit

Option A: Project-Specific (Recommended)

  1. Click "Download" above
  2. In your project, create the directory: .agent/skills/spring-boot-crud-patterns/
  3. Save the file as SKILL.md
  4. The agent will automatically discover the skill based on its description.

Option B: Global Installation (All Agents)

Save the file to these locations to make it available across all projects:

  • Claude Code: ~/.claude/skills/giuseppe-trisciuoglio/developer-kit/spring-boot-crud-patterns/SKILL.md
  • Cursor: ~/.cursor/skills/giuseppe-trisciuoglio/developer-kit/spring-boot-crud-patterns/SKILL.md
  • Antigravity: ~/.gemini/antigravity/skills/giuseppe-trisciuoglio/developer-kit/spring-boot-crud-patterns/SKILL.md

🚀 Install with CLI:
npx skills add giuseppe-trisciuoglio/developer-kit

Read the Master Guide: Mastering Agent Skills

Recommended Rules

View more rules

Recommended Workflows

View more workflows

Recommended MCP Servers

View more MCP servers

Take It Further

Maximize your productivity with these powerful resources

📋

Define Your Standards

Set up coding standards to ensure this workflow produces consistent, high-quality results.

Browse Rules Library
📖

Master Workflows

Learn how to create custom workflows, use Turbo Mode, and build your automation library.

Complete Guide

How to use this Skill in Claude Code & Cursor

For Claude Code (CLI)

To use this skill in Claude Code, copy the rule content into your project's custom instructions or follow our Add-Skill CLI guide. This ensures Claude follows your standards during every code generation.

For Cursor & Windsurf

For Cursor or Windsurf, individual skills are best used in the "Rules for AI" section. This specific unit helps the agent avoid backend development issues, leading to cleaner, more efficient code.

Why the skill format matters: the standardized Agent Skills format lets your AI agent load detailed instructions only when they are relevant, keeping your prompt clean while improving results.

Source & attribution

This skill is categorized under Backend Development and is published by Giuseppe Trisciuoglio, maintained in giuseppe-trisciuoglio/developer-kit.

← Browse All Agent Skills
Sponsored AI assistant. Recommendations may be paid.