spring-boot-crud-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSpring 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 and
spring-boot-starter-web.spring-boot-starter-data-jpa - Constructor injection enabled (Lombok or explicit constructors).
@RequiredArgsConstructor - Access to a relational database (Testcontainers recommended for integration tests).
- Familiarity with validation () and error handling (
jakarta.validation).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
快速入门工作流
- Establish Feature Structure
Createdirectories forfeature/<name>/,domain,application, andpresentation.infrastructure - Model the Aggregate
Define domain entities and value objects without Spring dependencies; capture invariants in methods such asandcreate.update - Expose Domain Ports
Declare repository interfaces indescribing persistence contracts.domain/repository - Provide Infrastructure Adapter
Implement Spring Data adapters inthat map domain models to JPA entities and delegate toinfrastructure/persistence.JpaRepository - Implement Application Services
Create transactional use cases underthat orchestrate aggregates, repositories, and mapping logic.application/service - Publish REST Controllers
Map DTO records under, expose endpoints with proper status codes, and wire validation annotations.presentation/rest - Validate with Tests
Run unit tests for domain logic and repository/service tests with Testcontainers for persistence verification.
Consult for complete code listings that align with each step.
references/examples-product-feature.md- 搭建特性结构
创建目录,包含feature/<名称>/、domain、application和presentation子目录。infrastructure - 建模聚合根
定义无Spring依赖的领域实体和值对象;在和create等方法中捕获不变量。update - 暴露领域端口
在中声明仓库接口,描述持久化契约。domain/repository - 提供基础设施适配器
在中实现Spring Data适配器,将领域模型映射到JPA实体,并委托给infrastructure/persistence。JpaRepository - 实现应用服务
在下创建事务型用例,协调聚合根、仓库和映射逻辑。application/service - 发布REST控制器
在下映射DTO记录,暴露带有正确状态码的端点,并配置验证注解。presentation/rest - 测试验证
为领域逻辑运行单元测试,为持久化验证运行基于Testcontainers的仓库/服务测试。
参考获取与每个步骤对应的完整代码清单。
references/examples-product-feature.mdImplementation Patterns
实现模式
Domain Layer
领域层
- Define immutable aggregates with factory methods () to centralize invariants.
Product.create - Use value objects (,
Money) to enforce type safety and encapsulate validation.Stock - Keep domain objects framework-free; avoid annotations in the domain package when using adapters.
@Entity
- 通过工厂方法(如)定义不可变聚合根,集中管理不变量。
Product.create - 使用值对象(如、
Money)强制执行类型安全并封装验证逻辑。Stock - 保持领域对象无框架依赖;使用适配器时,避免在领域包中添加注解。
@Entity
Application Layer
应用层
- Wrap use cases in classes using constructor injection and
@Service.@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., ) and custom queries for pagination or batch updates.
JpaRepository<ProductEntity, String> - Externalize persistence properties (naming strategies, DDL mode) via ; see
application.yml.references/spring-official-docs.md
- 实现适配器,在领域聚合根和JPA实体之间进行转换;为保证清晰性,优先使用MapStruct或手动映射器。
- 使用Spring Data接口(如)配置仓库,并为分页或批量更新编写自定义查询。
JpaRepository<ProductEntity, String> - 通过外部化持久化属性(命名策略、DDL模式);详见
application.yml。references/spring-official-docs.md
Presentation Layer
表示层
- Structure controllers by feature () and expose REST paths (
ProductController)./api/products - Return with appropriate codes:
ResponseEntityon POST,201 Createdon GET/PUT/PATCH,200 OKon DELETE.204 No Content - Apply on request DTOs and handle errors with
@Validor@ControllerAdvice.ResponseStatusException
- 按特性组织控制器(如),并暴露REST路径(如
ProductController)。/api/products - 返回带有合适状态码的:POST请求返回
ResponseEntity,GET/PUT/PATCH请求返回201 Created,DELETE请求返回200 OK。204 No Content - 在请求DTO上应用注解,并通过
@Valid或@ControllerAdvice处理错误。ResponseStatusException
Validation and Observability
验证与可观测性
- Write unit tests that assert domain invariants and repository contracts; refer to integration test snippets.
references/examples-product-feature.md - Use and Testcontainers to validate persistence mapping, pagination, and batch operations.
@DataJpaTest - Surface health and metrics through Spring Boot Actuator; monitor CRUD throughput and error rates.
- Log key actions at for lifecycle events (create, update, delete) and use structured logging for audit trails.
info
- 编写单元测试,断言领域不变量和仓库契约;参考中的集成测试片段。
references/examples-product-feature.md - 使用和Testcontainers验证持久化映射、分页和批量操作。
@DataJpaTest - 通过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 or pass
skills/spring-boot/spring-boot-crud-patterns/templates/; no fallback to built-ins. See--templates-dir <path>.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