spring-boot-crud-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Spring Boot CRUD Patterns

Spring Boot CRUD 模式

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.
交付与特性对齐的CRUD服务,在遵循Spring Boot 3.5+约定的同时分离领域层、应用层、表示层和基础设施层。本技能提炼了核心工作流,并将详细代码清单放在参考文件中,逐步展示。

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".
  • 为基于Spring Data JPA的增删改查工作流实现REST端点。
  • 遵循领域驱动设计(DDD)风格的架构,优化特性包,包含聚合根、仓库和应用服务。
  • 为外部客户端引入DTO记录、请求验证和控制器映射。
  • 诊断现有Spring Boot服务中的CRUD回归问题、仓库契约或事务边界。
  • 触发短语:"实现Spring CRUD控制器""优化基于特性的仓库""为JPA聚合根映射DTO""为REST列表端点添加分页"

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
    ).
  • 使用Spring Boot 3.5.x(或更高版本)的Java 17+项目,包含
    spring-boot-starter-web
    spring-boot-starter-data-jpa
    依赖。
  • 启用构造函数注入(使用Lombok
    @RequiredArgsConstructor
    或显式构造函数)。
  • 可访问关系型数据库(集成测试推荐使用Testcontainers)。
  • 熟悉验证(
    jakarta.validation
    )和错误处理(
    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.
  1. 搭建特性结构
    创建
    feature/<名称>/
    目录,包含
    domain
    application
    presentation
    infrastructure
    子目录。
  2. 建模聚合根
    定义无Spring依赖的领域实体和值对象;在
    create
    update
    等方法中捕获不变量。
  3. 暴露领域端口
    domain/repository
    中声明仓库接口,描述持久化契约。
  4. 提供基础设施适配器
    infrastructure/persistence
    中实现Spring Data适配器,将领域模型映射到JPA实体,并委托给
    JpaRepository
  5. 实现应用服务
    application/service
    下创建事务型用例,协调聚合根、仓库和映射逻辑。
  6. 发布REST控制器
    presentation/rest
    下映射DTO记录,暴露带有正确状态码的端点,并配置验证注解。
  7. 测试验证
    为领域逻辑运行单元测试,为持久化验证运行基于Testcontainers的仓库/服务测试。
参考
references/examples-product-feature.md
获取与每个步骤对应的完整代码清单。

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.
  • 通过工厂方法(如
    Product.create
    )定义不可变聚合根,集中管理不变量。
  • 使用值对象(如
    Money
    Stock
    )强制执行类型安全并封装验证逻辑。
  • 保持领域对象无框架依赖;使用适配器时,避免在领域包中添加
    @Entity
    注解。

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.
  • 将用例封装在使用构造函数注入和
    @Transactional
    @Service
    类中。
  • 将请求映射到领域操作,并通过领域仓库进行持久化。
  • 返回由专用映射器生成的响应DTO或记录,实现领域层与传输层的解耦。

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
    .
  • 实现适配器,在领域聚合根和JPA实体之间进行转换;为保证清晰性,优先使用MapStruct或手动映射器。
  • 使用Spring Data接口(如
    JpaRepository<ProductEntity, String>
    )配置仓库,并为分页或批量更新编写自定义查询。
  • 通过
    application.yml
    外部化持久化属性(命名策略、DDL模式);详见
    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
    .
  • 按特性组织控制器(如
    ProductController
    ),并暴露REST路径(如
    /api/products
    )。
  • 返回带有合适状态码的
    ResponseEntity
    :POST请求返回
    201 Created
    ,GET/PUT/PATCH请求返回
    200 OK
    ,DELETE请求返回
    204 No Content
  • 在请求DTO上应用
    @Valid
    注解,并通过
    @ControllerAdvice
    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.
  • 编写单元测试,断言领域不变量和仓库契约;参考
    references/examples-product-feature.md
    中的集成测试片段。
  • 使用
    @DataJpaTest
    和Testcontainers验证持久化映射、分页和批量操作。
  • 通过Spring Boot Actuator展示健康状态和指标;监控CRUD吞吐量和错误率。
  • 为生命周期事件(创建、更新、删除)在
    info
    级别记录关键操作,并使用结构化日志生成审计跟踪。

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.
  • 优先选择边界清晰的特性模块;将每个聚合根的领域、应用和表示代码放在一起。
  • 通过Java记录使DTO不可变;在服务边界转换领域类型。
  • 对写操作使用事务保护,在并发场景中使用乐观锁。
  • 标准化分页默认值(页码、大小、排序)并记录查询参数。
  • 在需要与消息传递或审计集成的场景中,捕获命令与事件之间的关联。

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.
  • 避免在控制器中直接暴露JPA实体,防止懒加载泄漏和序列化问题。
  • 不要将字段注入与构造函数注入混合使用;保持不可变性以简化测试。
  • 不要在控制器或仓库适配器中嵌入业务逻辑;应放在领域层/应用层。
  • 严格验证输入,防止约束违反并生成一致的错误负载。
  • 在部署 schema 变更前,确保迁移(Liquibase/Flyway)与聚合根的演进保持一致。

References

参考资料

  • HTTP method matrix, annotation catalog, DTO patterns.
  • Progressive examples from starter to advanced feature implementation.
  • Excerpts from official Spring guides and Spring Boot reference documentation.
  • Python generator to scaffold CRUD boilerplate from entity spec. 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
  • 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
  • HTTP方法矩阵、注解目录、DTO模式。
  • 从入门到高级特性实现的渐进式示例。
  • 官方Spring指南和Spring Boot参考文档摘录。
  • 从实体规范生成CRUD模板代码的Python生成器。 使用方法:
    python skills/spring-boot/spring-boot-crud-patterns/scripts/generate_crud_boilerplate.py --spec entity.json --package com.example.product --output ./generated
  • 所需模板:将.tpl文件放在
    skills/spring-boot/spring-boot-crud-patterns/templates/
    目录下,或通过
    --templates-dir <路径>
    指定;不回退到内置模板。详见
    templates/README.md
  • 使用指南:references/generator-usage.md
  • 示例规范:
    skills/spring-boot/spring-boot-crud-patterns/assets/specs/product.json
  • 带关联关系的示例:
    skills/spring-boot/spring-boot-crud-patterns/assets/specs/product_with_rel.json