A complete, hands-on walkthrough of building a CRUD REST API with Spring Boot 3.5.x (Spring Framework 6, Java 17), organized into Git branches that progressively cover most of the key concepts in the Spring Boot ecosystem.
The data model follows this EER schema: categories → products → orders ← customers.
This document is the complete specification of the project: it is meant to be followed step by step to implement each branch.
Repository: https://github.com/EdgarEldy/spring-boot-tutorial
- Tech stack
- Data model
- Branching strategy
- Project structure
- Standard response format
- Spring AOP
- feature/core-architecture
- feature/products
- feature/product-images
- feature/customers
- feature/orders
- feature/auth
- feature/roles-permissions
- feature/token-management
- feature/user-management
- feature/product-images
- feature/shopping-cart
- feature/order-checkout
- feature/order-notifications
- feature/order-authorization
- feature/integration
- Order of work
- Code conventions
- Concepts covered
- How to follow this tutorial
| Component | Choice |
|---|---|
| Framework | Spring Boot 3.5.x (Spring Framework 6) |
| Language | Java 17 (LTS) |
| Build | Maven |
| Database | PostgreSQL 16 (via Docker Compose) |
| Migrations | Flyway |
| ORM | Spring Data JPA / Hibernate |
| DTO mapping | MapStruct + Lombok |
| Validation | Jakarta Bean Validation |
| API documentation | springdoc-openapi (Swagger UI) |
| Monitoring | Spring Boot Actuator |
| Security | Spring Security 6 + JWT (jjwt) |
| Aspect-oriented programming | Spring AOP |
| Cache | Spring Cache abstraction + Caffeine |
| Tests | JUnit 5, Mockito, Testcontainers, AssertJ |
| CI/CD | GitHub Actions |
| Containerization | Docker, docker-compose |
Base model (branches feature/core-architecture through feature/orders):
categories (id, category_name)
│ 1
│
│ N
products (id, category_id, product_name, unit_price)
│ 1
│
│ N
orders (id, customer_id, product_id, quantity, total)
│ N
│
│ 1
customers (id, first_name, last_name, telephone, email, address)
The e-commerce extension (branches feature/auth through feature/integration) adds app_users, roles, permissions, token tables, product_images, carts, cart_items, and replaces the single-line order model with an order_items snapshot table.
categories
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| category_name | VARCHAR(255) | NOT NULL |
products
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| category_id | BIGINT | FK → categories.id, NOT NULL |
| product_name | VARCHAR(255) | NOT NULL |
| unit_price | NUMERIC(12,2) | NOT NULL, > 0 — migrated from FLOAT in V13 for exact monetary arithmetic |
| description | VARCHAR(500) | nullable — added in V13 |
| active | BOOLEAN | NOT NULL DEFAULT TRUE — added in V13; excluded from create/update payloads |
customers
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| first_name | VARCHAR(255) | NOT NULL |
| last_name | VARCHAR(255) | NOT NULL |
| telephone | VARCHAR(50) | NOT NULL |
| VARCHAR(255) | NOT NULL, UNIQUE, valid email format | |
| address | VARCHAR(255) | NOT NULL |
orders (extended in feature/orders, feature/order-checkout, and feature/order-authorization)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| customer_id | BIGINT | FK → customers.id, nullable - legacy CRUD orders only |
| product_id | BIGINT | FK → products.id, nullable - legacy CRUD orders only |
| quantity | INT | nullable - legacy CRUD orders only |
| total | NUMERIC(12,2) | nullable - legacy column, made nullable in V15 after backfill |
| order_number | VARCHAR(36) | NOT NULL UNIQUE — UUID generated at creation, added in V14 |
| status | VARCHAR(20) | NOT NULL DEFAULT 'PENDING' — PENDING, CONFIRMED, CANCELLED; added in V14 |
| total_amount | NUMERIC(12,2) | NOT NULL — sum of all OrderItem lines; added in V14 |
| user_id | BIGINT | FK → app_users.id, nullable — added in V18; set only for checkout orders; legacy CRUD orders have no user_id |
order_items (added in V14)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| order_id | BIGINT | FK → orders.id, NOT NULL |
| product_id | BIGINT | FK → products.id, NOT NULL |
| quantity | INT | NOT NULL, > 0 |
| unit_price | NUMERIC(12,2) | NOT NULL — snapshot at order time |
product_images (added in V16)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| product_id | BIGINT | FK → products.id, NOT NULL |
| filename | VARCHAR(255) | NOT NULL |
| url | VARCHAR(512) | NOT NULL |
| is_primary | BOOLEAN | NOT NULL DEFAULT FALSE — partial unique index enforces at most one primary per product |
carts (added in V17)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| user_id | BIGINT | FK → app_users.id, NOT NULL UNIQUE — one cart per user |
cart_items (added in V17)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| cart_id | BIGINT | FK → carts.id, NOT NULL |
| product_id | BIGINT | FK → products.id, NOT NULL |
| quantity | INT | NOT NULL, > 0 |
app_users (V2: base columns; V7: role_user join; V8: account_locked; V9: first_name/last_name)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| username | VARCHAR(255) | NOT NULL UNIQUE |
| VARCHAR(255) | NOT NULL UNIQUE | |
| password | VARCHAR(255) | NOT NULL |
| enabled | BOOLEAN | NOT NULL DEFAULT FALSE |
| account_locked | BOOLEAN | NOT NULL DEFAULT FALSE — added in V8 |
| first_name | VARCHAR(100) | nullable — added in V9 |
| last_name | VARCHAR(100) | nullable — added in V9 |
roles (added in V5 as JPA entity, replacing the Role enum from feature/auth)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| name | VARCHAR(50) | NOT NULL UNIQUE |
permissions (added in V5)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| resource | VARCHAR(100) | NOT NULL |
| action | VARCHAR(50) | NOT NULL |
| UNIQUE | (resource, action) |
role_user (join table, added in V7)
| Column | Type | Constraints |
|---|---|---|
| role_id | BIGINT | FK → roles.id |
| user_id | BIGINT | FK → app_users.id |
role_permission (join table, added in V5)
| Column | Type | Constraints |
|---|---|---|
| role_id | BIGINT | FK → roles.id |
| permission_id | BIGINT | FK → permissions.id |
activation_tokens (added in V6)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| token | VARCHAR(255) | NOT NULL UNIQUE |
| user_id | BIGINT | FK → app_users.id, NOT NULL |
| expires_at | TIMESTAMP | NOT NULL |
| used | BOOLEAN | NOT NULL DEFAULT FALSE |
blacklisted_tokens (added in V6 — no user FK; identifies revoked JWTs by jti)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| jti | VARCHAR(255) | NOT NULL UNIQUE |
| invalidated_at | TIMESTAMP | NOT NULL |
password_reset_tokens (added in V6)
| Column | Type | Constraints |
|---|---|---|
| id | BIGINT | PK, auto-increment |
| token | VARCHAR(255) | NOT NULL UNIQUE |
| user_id | BIGINT | FK → app_users.id, NOT NULL |
| expires_at | TIMESTAMP | NOT NULL |
| used | BOOLEAN | NOT NULL DEFAULT FALSE |
| Branch | Role |
|---|---|
master |
Stable, production-ready code. No direct commits only merges from develop. |
develop |
Integration branch. All feature/* branches are merged here before master. |
feature/core-architecture |
Technical foundation: project structure, configuration, baseline security, Docker, CI. |
feature/products |
Category and Product CRUD. |
feature/customers |
Customer CRUD. |
feature/orders |
Order CRUD, business logic linking products and customers. |
feature/auth |
Authentication and authorization (Spring Security + JWT). |
feature/roles-permissions |
Fine-grained Role/Permission CRUD and method-level security (@PreAuthorize, custom PermissionEvaluator). |
feature/token-management |
Activation, blacklisted and password-reset tokens; async email (@Async); scheduled cleanup (@Scheduled). |
feature/user-management |
AppUser CRUD (admin), user-role assignment (role_user join table, V7), account activation/password-reset flows. |
feature/product-images |
Product image upload: ProductImage entity (V15), FileStorageService, POST/DELETE /api/v1/products/{id}/images (ROLE_ADMIN). |
feature/shopping-cart |
Persistent shopping cart: Cart/CartItem entities (V16), full CRUD endpoints tied to the authenticated user (@AuthenticationPrincipal). |
feature/order-checkout |
Atomic checkout: POST /api/v1/orders drains the cart and creates an Order with OrderItem lines in a single transaction. Introduces order_items table (V14), order_number, status, total_amount. |
feature/order-notifications |
Email notification on order placement via OrderEmailService (@Async) and NotificationProperties (@ConfigurationProperties). |
feature/order-authorization |
Role-based order access: users see only their own orders, admins see all; PATCH /api/v1/orders/{id}/status restricted to ROLE_ADMIN. |
feature/integration |
Merges feature/product-images into the main chain; end-to-end EcommerceIntegrationTest covering the full flow from registration to order status update. |
Each feature is developed on its own branch, then merged into develop via a documented Pull Request (even solo), to keep a clear, educational trace of each step. In practice, on this particular repository, merges have been done locally (git merge) rather than through an actual GitHub Pull Request: this section describes the intended workflow for anyone forking or following along, not necessarily every merge already present in this history.
The tree below shows the full final state across all branches.
spring-boot-tutorial/
├── src/
│ ├── main/
│ │ ├── java/com/edgareldy/springboottutorial/
│ │ │ ├── SpringBootTutorialApplication.java
│ │ │ ├── config/
│ │ │ │ ├── OpenApiConfig.java
│ │ │ │ ├── SecurityConfig.java
│ │ │ │ ├── MethodSecurityConfig.java
│ │ │ │ ├── JacksonConfig.java
│ │ │ │ ├── CorsConfig.java
│ │ │ │ ├── CacheConfig.java
│ │ │ │ ├── JpaAuditingConfig.java
│ │ │ │ ├── AsyncConfig.java
│ │ │ │ ├── SchedulingConfig.java
│ │ │ │ └── StorageConfig.java
│ │ │ ├── entity/
│ │ │ │ ├── Category.java
│ │ │ │ ├── Product.java
│ │ │ │ ├── ProductImage.java
│ │ │ │ ├── Customer.java
│ │ │ │ ├── Order.java
│ │ │ │ ├── OrderItem.java
│ │ │ │ ├── OrderStatus.java (enum)
│ │ │ │ ├── Cart.java
│ │ │ │ ├── CartItem.java
│ │ │ │ └── user/
│ │ │ │ ├── AppUser.java
│ │ │ │ ├── Role.java
│ │ │ │ ├── Permission.java
│ │ │ │ ├── ActivationToken.java
│ │ │ │ ├── BlacklistedToken.java
│ │ │ │ └── PasswordResetToken.java
│ │ │ ├── repository/
│ │ │ │ ├── CategoryRepository.java
│ │ │ │ ├── ProductRepository.java
│ │ │ │ ├── ProductImageRepository.java
│ │ │ │ ├── CustomerRepository.java
│ │ │ │ ├── OrderRepository.java
│ │ │ │ ├── CartRepository.java
│ │ │ │ ├── CartItemRepository.java
│ │ │ │ ├── AppUserRepository.java
│ │ │ │ ├── RoleRepository.java
│ │ │ │ ├── PermissionRepository.java
│ │ │ │ ├── ActivationTokenRepository.java
│ │ │ │ ├── BlacklistedTokenRepository.java
│ │ │ │ └── PasswordResetTokenRepository.java
│ │ │ ├── dto/
│ │ │ │ ├── common/
│ │ │ │ │ ├── ApiResponse.java
│ │ │ │ │ └── PageResponse.java
│ │ │ │ ├── category/ (CategoryRequest, CategoryResponse)
│ │ │ │ ├── product/ (ProductRequest, ProductResponse)
│ │ │ │ ├── image/ (ProductImageResponse)
│ │ │ │ ├── customer/ (CustomerRequest, CustomerResponse)
│ │ │ │ ├── order/ (OrderRequest, OrderResponse, OrderItemResponse, OrderStatusUpdateRequest)
│ │ │ │ ├── cart/ (CartItemRequest, CartItemUpdateRequest, CartItemResponse, CartResponse)
│ │ │ │ ├── role/ (RoleRequest, RoleResponse, UpdateRolePermissionsRequest)
│ │ │ │ ├── permission/ (PermissionRequest, PermissionResponse)
│ │ │ │ ├── user/ (UserResponse, UpdateProfileRequest, UpdateUserRolesRequest)
│ │ │ │ └── auth/ (RegisterRequest, LoginRequest, AuthResponse)
│ │ │ ├── mapper/
│ │ │ │ ├── CategoryMapper.java
│ │ │ │ ├── ProductMapper.java
│ │ │ │ ├── ProductImageMapper.java
│ │ │ │ ├── CustomerMapper.java
│ │ │ │ ├── OrderMapper.java
│ │ │ │ ├── CartMapper.java
│ │ │ │ ├── RoleMapper.java
│ │ │ │ ├── PermissionMapper.java
│ │ │ │ └── AppUserMapper.java
│ │ │ ├── service/
│ │ │ │ ├── CategoryService.java
│ │ │ │ ├── ProductService.java
│ │ │ │ ├── FileStorageService.java
│ │ │ │ ├── ProductImageService.java
│ │ │ │ ├── CustomerService.java
│ │ │ │ ├── OrderService.java
│ │ │ │ ├── OrderEmailService.java
│ │ │ │ ├── CartService.java
│ │ │ │ ├── AuthService.java
│ │ │ │ ├── UserService.java
│ │ │ │ ├── RoleService.java
│ │ │ │ ├── PermissionService.java
│ │ │ │ ├── EmailService.java
│ │ │ │ ├── ActivationTokenService.java
│ │ │ │ ├── PasswordResetTokenService.java
│ │ │ │ ├── BlacklistedTokenService.java
│ │ │ │ └── impl/
│ │ │ │ ├── CategoryServiceImpl.java
│ │ │ │ ├── ProductServiceImpl.java
│ │ │ │ ├── LocalFileStorageService.java
│ │ │ │ ├── ProductImageServiceImpl.java
│ │ │ │ ├── CustomerServiceImpl.java
│ │ │ │ ├── OrderServiceImpl.java
│ │ │ │ ├── OrderEmailServiceImpl.java
│ │ │ │ ├── CartServiceImpl.java
│ │ │ │ ├── AuthServiceImpl.java
│ │ │ │ ├── UserServiceImpl.java
│ │ │ │ ├── RoleServiceImpl.java
│ │ │ │ ├── PermissionServiceImpl.java
│ │ │ │ ├── EmailServiceImpl.java
│ │ │ │ ├── ActivationTokenServiceImpl.java
│ │ │ │ ├── PasswordResetTokenServiceImpl.java
│ │ │ │ └── BlacklistedTokenServiceImpl.java
│ │ │ ├── controller/
│ │ │ │ ├── CategoryController.java
│ │ │ │ ├── ProductController.java
│ │ │ │ ├── CustomerController.java
│ │ │ │ ├── OrderController.java
│ │ │ │ ├── CartController.java
│ │ │ │ ├── AuthController.java
│ │ │ │ ├── UserController.java
│ │ │ │ ├── RoleController.java
│ │ │ │ └── PermissionController.java
│ │ │ ├── exception/
│ │ │ │ ├── ResourceNotFoundException.java
│ │ │ │ ├── BusinessRuleException.java
│ │ │ │ ├── InvalidTokenException.java
│ │ │ │ └── GlobalExceptionHandler.java
│ │ │ ├── security/
│ │ │ │ ├── JwtService.java
│ │ │ │ ├── JwtProperties.java
│ │ │ │ ├── JwtAuthFilter.java
│ │ │ │ ├── UserDetailsServiceImpl.java
│ │ │ │ ├── JwtAuthenticationEntryPoint.java
│ │ │ │ ├── JwtAccessDeniedHandler.java
│ │ │ │ └── CustomPermissionEvaluator.java
│ │ │ ├── validation/
│ │ │ │ ├── password/ (ValidPassword, PasswordValidator, PasswordsMatch, PasswordsMatchValidator)
│ │ │ │ └── unique/ (Unique, UniqueValidator)
│ │ │ ├── event/
│ │ │ │ ├── OrderCreatedEvent.java
│ │ │ │ └── OrderCreatedEventListener.java
│ │ │ ├── aspect/
│ │ │ │ ├── LoggingAspect.java
│ │ │ │ ├── ExecutionTimeAspect.java
│ │ │ │ └── RepositoryAuditAspect.java
│ │ │ ├── token/
│ │ │ │ ├── SecureTokenGenerator.java
│ │ │ │ └── TokenCleanupScheduler.java
│ │ │ └── actuator/
│ │ │ └── AppInfoEndpoint.java
│ │ └── resources/
│ │ ├── application.yml
│ │ ├── application-dev.yml
│ │ ├── application-test.yml
│ │ ├── application-prod.yml
│ │ └── db/migration/
│ │ ├── V1__init_schema.sql
│ │ ├── V2__init_users_and_roles.sql
│ │ ├── V3__add_product_version.sql
│ │ ├── V4__add_category_audit_columns.sql
│ │ ├── V5__roles_permissions.sql
│ │ ├── V6__tokens.sql
│ │ ├── V7__role_user.sql
│ │ ├── V8__add_account_locked.sql
│ │ ├── V9__add_name_fields_to_app_users.sql
│ │ ├── V13__add_product_description_active_decimal_price.sql
│ │ ├── V14__evolve_orders_domain.sql
│ │ ├── V15__make_orders_total_legacy_nullable.sql
│ │ ├── V16__create_product_images.sql
│ │ ├── V17__create_cart_tables.sql
│ │ └── V18__add_user_id_to_orders.sql
│ └── test/
│ └── java/com/edgareldy/springboottutorial/
│ ├── controller/ (MockMvc tests)
│ ├── service/ (Mockito unit tests)
│ ├── repository/ (@DataJpaTest / Testcontainers)
│ └── integration/ (EcommerceIntegrationTest, OrderAuthorizationTest, SecurityAuthorizationTest)
├── docker-compose.yml
├── Dockerfile
├── .github/workflows/ci.yml
├── pom.xml
└── README.md
Every API response (success and error alike) is wrapped in a generic ApiResponse<T> DTO, defined in dto/common/ApiResponse.java, to keep a consistent contract across all endpoints.
public record ApiResponse<T>(
boolean success,
String message,
T data,
Instant timestamp
) {
public static <T> ApiResponse<T> success(T data, String message) {
return new ApiResponse<>(true, message, data, Instant.now());
}
public static <T> ApiResponse<T> error(String message) {
return new ApiResponse<>(false, message, null, Instant.now());
}
}- On list endpoints,
dataholds aPageResponse<T>(paginated content:content,page,size,totalElements,totalPages) instead of a plainList<T>. - On error,
GlobalExceptionHandlerreturns anApiResponse<ProblemDetail>withsuccess=false:dataholds a standard RFC 7807ProblemDetail(Spring 6's built-in class,org.springframework.http.ProblemDetail), not a project-specific error DTO. Field validation errors are attached as afieldErrorsextension property. - Every DTO field is exposed in the JSON contract as snake_case (e.g.
product_name,unit_price,category_id), decoupled from the Java field's own camelCase name via an explicit@JsonPropertyon each record component. Controllers returnResponseEntity<ApiResponse<T>>, notApiResponse<T>directly:ApiResponse<T>still wraps every response body,ResponseEntityonly adds control over the HTTP status code alongside it. - Success response example:
{
"success": true,
"message": "Product created successfully",
"data": { "id": 12, "product_name": "Mechanical keyboard", "unit_price": 79.99, "category_id": 3 },
"timestamp": "2026-07-02T10:15:30Z"
}- Error response example:
{
"success": false,
"message": "Product not found",
"data": {
"type": "about:blank",
"title": "Not Found",
"status": 404,
"detail": "Product not found",
"instance": "/api/v1/products/99"
},
"timestamp": "2026-07-02T10:16:05Z"
}The project uses Spring AOP to illustrate aspect-oriented programming, kept out of any business logic in services/controllers.
- Dependency:
spring-boot-starter-aop LoggingAspect(aspect/LoggingAspect.java):@Aroundadvice on all@Servicebeans (pointcutexecution(* com.edgareldy.springboottutorial.service..*(..))), logs method entry/exit, arguments, and thrown exceptionsExecutionTimeAspect(aspect/ExecutionTimeAspect.java):@Aroundadvice on controller methods, measures and logs the execution time of each HTTP requestRepositoryAuditAspect(aspect/RepositoryAuditAspect.java): on the repository layer, the four advice types the other two aspects don't use:@Before/@Afteraround every repository call,@AfterReturningonsavespecifically,@AfterThrowingon any repository exception- Can later be reused for auditing (e.g. tracing who created/modified an order) without polluting business code
Technical foundation shared by the whole project, to be merged first into develop. Originally named feature/config; renamed to better reflect that it lays out the whole architectural skeleton (config, cross-cutting concerns, containerization, CI), not just configuration files.
- Initialize the project via Spring Initializr (Maven, Java 17, Spring Boot 3.5.16)
- Dependencies:
spring-boot-starter-web,spring-boot-starter-data-jpa,spring-boot-starter-validation,spring-boot-starter-actuator,spring-boot-starter-security,spring-boot-starter-aop,spring-boot-starter-mail,spring-boot-devtools,flyway-core,flyway-database-postgresql,postgresqldriver,lombok,mapstruct+mapstruct-processor,springdoc-openapi-starter-webmvc-ui,jjwt-api/jjwt-impl/jjwt-jackson - Test dependencies:
spring-boot-starter-test,spring-security-test,testcontainers(junit-jupiter, postgresql) - Create the package tree shown above
-
application.yml: shared configuration (app name, port, JSON date format) -
application-dev.yml: local datasource,spring.jpa.show-sql=true, Flyway enabled,spring.mailpointing to MailHog (localhost:1025) -
application-test.yml: Testcontainers datasource -
application-prod.yml: datasource via environment variables, JSON logs,spring.mailvia env vars (MAIL_HOST,MAIL_PORT,MAIL_USERNAME,MAIL_PASSWORD) - Flyway script
V1__init_schema.sql(categories, products, customers, orders tables with FKs) -
InvalidTokenException: custom unchecked exception for expired or invalid tokens (used byfeature/token-management) -
GlobalExceptionHandler(@RestControllerAdvice): handlesResourceNotFoundException(404),MethodArgumentNotValidException(400, field details),BusinessRuleException(422),InvalidTokenException(400),BadCredentialsException(401),LockedException(401),DisabledException(401),AccessDeniedException(403),AuthenticationException(401),ObjectOptimisticLockingFailureException(409), genericException(500) - Error payload as a standard RFC 7807
ProblemDetail(org.springframework.http.ProblemDetail):type,title,status,detail,instance, plus afieldErrorsextension property on validation failures - Generic
ApiResponse<T>(dto/common/ApiResponse.java) andPageResponse<T>(dto/common/PageResponse.java) DTOs, used to wrap every controller response -
LoggingAspectandExecutionTimeAspect(aspect/): logging and execution-time measurement via Spring AOP (see Spring AOP);LoggingAspectuses reflection-based masking to redact fields annotated@SensitiveFieldbefore logging arguments and return values -
OpenApiConfig: title, description, version, JWT security scheme in Swagger UI - Actuator: expose
health,info,metricsin dev (plus a customappinfoendpoint, seeAppInfoEndpoint);healthonly in prod - Structured logging (
logback-spring.xmland Actuator ECS/JSON config, combined) -
CorsConfig: allowlocalhost:4200in dev; allowed methods includePATCH -
AsyncConfig:@EnableAsyncwith a dedicatedThreadPoolTaskExecutorfor email-sending tasks -
SchedulingConfig:@EnableSchedulingto activate@Scheduledtasks (used byfeature/token-management) -
JpaAuditingConfig(@EnableJpaAuditing): native Spring Data JPA auditing support, consumed byCategoryonfeature/products -
spring-boot-devtools: automatic restart and other dev-only conveniences, disabled outside local runs - Multi-stage
Dockerfile(Maven build + lightweight JRE image) -
docker-compose.yml:appservice +dbservice (PostgreSQL 16) +mailhogservice (local SMTP for email testing) with volumes and environment variables read from.env -
.env.example: template listing all required environment variables includingMAIL_HOST,MAIL_PORT,MAIL_USERNAME,MAIL_PASSWORD -
.github/workflows/ci.yml: Maven build + tests on every push/PR - Branch
READMEexplaining the configuration choices (see below)
- Spring Boot 3.5.16, not 4.1.x. The project was first scoped around Spring Boot 4.1 / Spring Framework 7, but springdoc-openapi had no release compatible with Spring Framework 7 on Maven Central at implementation time. Spring Boot 3.5.16 (Spring Framework 6) is fully compatible with every required dependency (springdoc, MapStruct, jjwt) and is still an actively maintained line, so it was chosen instead.
dependencyManagementexplicitly importsspring-boot-dependenciesas${project.parent.version}, in addition to inheriting it via<parent>. This is redundant (the parent POM already provides the same bill of materials) but was requested explicitly to make version management visible directly independencyManagement.hibernate.ddl-autoisvalidatein every profile, neverupdateorcreate. Flyway'sV1__init_schema.sqlis the single source of truth for the schema; Hibernate only checks that entity mappings agree with it. This avoids the classic drift where a forgotten entity annotation silently alters the schema in one environment but not another.- Structured logging combines two mechanisms on purpose.
logback-spring.xmlincludes Spring Boot's own default appenders (defaults.xml,console-appender.xml) instead of redefining them, and adds a prod-onlyfile-appender.xmlinclude via<springProfile name="prod">. The actual JSON formatting comes from Spring Boot 3.4+'s nativelogging.structured.format.console/.fileproperties (set toecsinapplication-prod.yml), so no extra dependency (e.g.logstash-logback-encoder) or hand-written JSON encoder was needed. CorsConfigis annotated@Profile("dev"). Only the local Angular dev server (localhost:4200) gets a CORS exemption; prod is expected to declare its own, narrower policy once a real frontend origin exists.- Testcontainers only, no H2.
application-test.ymldeclares no datasource at all:TestcontainersConfiguration's@ServiceConnectionPostgreSQLContainerbean wires the datasource automatically. Using real PostgreSQL in tests (instead of an in-memory H2 database) avoids behavioral differences between the two engines (types, constraints, SQL dialect) that would otherwise only surface in production. GlobalExceptionHandlerreturnsApiResponse<ProblemDetail>, not a project-specific error DTO.ProblemDetailis Spring 6's built-in RFC 7807 type; using it directly asApiResponse<T>'s type parameter demonstrates the standard without abandoning the project's own envelope, sinceApiResponse<T>still wraps every response (success and error alike). Only the shape ofdataon errors changed; every success response (ApiResponse<CategoryResponse>,ApiResponse<PageResponse<ProductResponse>>, etc.) is untouched.
Includes Category and Product, given their direct link in the model.
| Method | URL | Description |
|---|---|---|
| GET | /api/v1/categories |
Paginated list of categories |
| GET | /api/v1/categories/{id} |
Category detail, including its associated products |
| POST | /api/v1/categories |
Create a category |
| PUT | /api/v1/categories/{id} |
Update a category |
| DELETE | /api/v1/categories/{id} |
Delete a category |
| GET | /api/v1/products |
Paginated list, filterable by categoryId, productName (contains), minPrice/maxPrice, sortable by productName/unitPrice |
| GET | /api/v1/products/{id} |
Product detail |
| POST | /api/v1/products |
Create a product |
| PUT | /api/v1/products/{id} |
Update a product |
| DELETE | /api/v1/products/{id} |
Delete a product |
-
Category,Productentities with@OneToMany/@ManyToOnerelation (LAZYloading) -
CategoryRepository,ProductRepository(Spring Data JPA) with derived queries (findByCategoryId) and one@QueryusingJOIN FETCH - DTOs
CategoryRequest/CategoryResponse,ProductRequest/ProductResponse -
Product.unitPriceusesBigDecimal(Java) backed byNUMERIC(12,2)(SQL, V13 migration) for exact monetary arithmetic -
Product.description(nullableVARCHAR(500)) andProduct.active(boolean, defaulttrue, V13 migration) - Corresponding MapStruct mappers
-
CategoryService,ProductServiceinterfaces (contracts) and theirCategoryServiceImpl,ProductServiceImplimplementations inservice/impl, annotated@Service, with@Transactionalon writes - Business rule: a category containing products cannot be deleted (
BusinessRuleException) -
CategoryController,ProductController: REST CRUD + pagination (Pageable) + sorting - OpenAPI documentation (
@Operation,@ApiResponse) on every endpoint - Service unit tests (Mockito)
-
@DataJpaTestrepository tests - MockMvc controller integration tests
- Optimistic locking (
@Version) onProduct, withOptimisticLockingFailureExceptionmapped to 409 - Dynamic filtering (
Specification/JpaSpecificationExecutor) onProduct:productName/minPrice/maxPrice, in addition tocategoryId - Native JPA auditing (
@CreatedDate/@LastModifiedDate) onCategory, viafeature/core-architecture'sJpaAuditingConfig - Controllers return
ResponseEntity<ApiResponse<T>>; every DTO field is exposed in JSON as snake_case via@JsonProperty -
CategoryResponse.products(the category's associatedProducts) on the detail endpoint only
CategoryResponse.productsis only populated byGET /api/v1/categories/{id}, never by the paginated list.CategoryRepository.findByIdWithProducts(LEFT JOIN FETCH) backs the detail endpoint; the list endpoint'sCategoryMapper.toResponseexplicitly setsproductsto an empty list rather than touching the entity's lazy, unfetched collection, avoiding an N+1 across a full page of categories.- Snake_case JSON via
@JsonPropertyper field, not a global Jackson naming strategy. Keeps every Java field/record component camelCase (idiomatic, and MapStruct keeps matching DTO fields to entity fields by name automatically) while the public JSON contract is snake_case. - Flyway migrations on this branch are numbered
V3,V4andV13, skippingV2andV5-V12.V2is reserved forfeature/auth;V5-V12are reserved for branches fromfeature/auththroughfeature/user-managementthat appear further up the merge chain.V13addsdescription,activeand migratesunit_pricefromREALtoNUMERIC(12,2)on the products table. ProductServiceImpl.findAllonly falls back to aSpecification-based query whenproductName/minPrice/maxPriceis supplied. The plain andcategoryId-only cases keep using the existing@EntityGraph-backed repository methods; theSpecificationpath has no fetch join forcategory, an accepted N+1 risk kept simple rather than complicatingProductSpecificationswith one, and scoped only to requests that actually use the new filters.minPrice/maxPricequery parameters andunitPricethroughout the stack useBigDecimal.ProductSpecifications.priceBetween,ProductService.findAll,ProductController.findAlland all DTOs have been updated fromFloat/floattoBigDecimalto prevent rounding at the HTTP deserialization boundary.Product.activeis not writable fromProductRequest.ProductMapper.toEntityandupdateEntityFromRequestboth ignoreactiveto prevent a create/update call from accidentally clearing the flag. Activation and deactivation are managed separately.
Adds image upload and management for products. Branches from feature/products and is
independent of feature/orders. Introduces a local file storage abstraction that can be
replaced by S3 or any other backend by swapping the FileStorageService implementation.
| Method | URL | Description |
|---|---|---|
| POST | /api/v1/products/{id}/images |
Upload an image for a product (multipart/form-data) |
| DELETE | /api/v1/products/{id}/images/{imageId} |
Remove an image from a product |
GET /api/v1/products/{id} now includes an images array in the response (empty on the
paginated list, populated on the detail endpoint).
- Migration
V16__create_product_images.sql:product_imagestable withis_primarypartial unique index (WHERE is_primary = TRUE),ON DELETE CASCADEto products -
ProductImageentity with@ManyToOne(LAZY)toProduct, JPA auditing -
StorageProperties(@ConfigurationProperties(prefix = "app.storage")) andStorageConfig -
FileStorageServiceinterface +LocalFileStorageServiceimplementation (UUID filenames, extension and MIME type validation, size limit, path traversal guard) -
ProductImageRepositorywithfindByProductIdOrderByDisplayOrderAscandfindByProductIdAndPrimaryTrue -
ProductImageResponseDTO (snake_case JSON via@JsonProperty) -
ProductImageMapper -
ProductImageServiceinterface +ProductImageServiceImpl: upload, primary-flag swap, ownership check on delete -
ProductServiceImpl.findByIdupdated to load images and delegate toProductMapper.toDetailResponse -
ProductResponsegainsList<ProductImageResponse> images(empty on list, populated on detail) -
ProductControllergainsPOST /{id}/imagesandDELETE /{id}/images/{imageId}endpoints - Tests:
ProductImageServiceImplTest,LocalFileStorageServiceTest, image endpoint tests inProductControllerTest
app.storage.upload-dirdefaults to./uploads/products(overridable viaAPP_STORAGE_UPLOAD_DIR). In a Docker deployment, mount a persistent volume at that path so uploaded files survive container restarts.app.storage.max-file-size-mbis set to 5. Accepted formats:jpg,jpeg,png,webp.ProductResponse.imagesis populated only onGET /api/v1/products/{id}. The paginated list (findAll) usesProductMapper.toResponse, which always returns an empty list, keeping list requests free of an N+1 onproduct_images. The detail endpoint loads images viaProductImageRepository.findByProductIdOrderByDisplayOrderAscand passes the list toProductMapper.toDetailResponse.findByIdresult is cached (@Cacheable("products")) including the image list. A cache eviction onupdate/deleteensures stale image data does not linger, but adding or removing an image does not evict the product cache. The product detail will serve the cached (stale) image list until the cache entry expires (TTL fromCacheConfig). This is an accepted simplification for this tutorial.boolean primaryonProductImage(columnis_primary). Lombok generatesisPrimary()as the getter (JavaBeans convention), which MapStruct maps as propertyprimary, matching the record component name inProductImageResponse. Naming the fieldisPrimarywould have caused a mismatch and an unmapped-property warning.- Migration is
V16, notV15.V14andV15are reserved forfeature/orders(this branch does not depend onfeature/orders). UsingV16avoids a Flyway conflict when both branches merge into an integration branch.
| Method | URL | Description |
|---|---|---|
| GET | /api/v1/customers |
Paginated list, search by name (?search=) |
| GET | /api/v1/customers/{id} |
Customer detail |
| POST | /api/v1/customers |
Create a customer |
| PUT | /api/v1/customers/{id} |
Update a customer |
| DELETE | /api/v1/customers/{id} |
Delete a customer |
-
Customerentity -
CustomerRepositorywith search (findByEmail, derived query on first/last name) - DTOs
CustomerRequest/CustomerResponsewith validation (valid email, phone format) -
CustomerMapper -
CustomerServiceinterface andCustomerServiceImplimplementation (inservice/impl): email uniqueness check on create and update -
CustomerController - Unit and integration tests
-
CustomerControllerreturnsResponseEntity<ApiResponse<T>>;CustomerRequest/CustomerResponsefields exposed in JSON as snake_case via@JsonProperty
CustomerResponsedoes not carry the customer's ordered products on this branch.Order(and therefore any customer-to-product link) does not exist yet here; it is introduced byfeature/orders, which is where that association becomes queryable and where this is implemented instead.
Orderentity:@ManyToOnetoCustomerandProduct(both nullable for historical compatibility),@OneToMany(cascade = ALL, orphanRemoval = true)toOrderItem,@Enumerated(EnumType.STRING) OrderStatus status(defaultPENDING),BigDecimal totalAmount,String orderNumber(unique, generated asORD-+ 8-char UUID prefix on create).OrderItementity: product snapshot at order time (productName,unitPriceasNUMERIC(12,2)),quantity,subtotal; child ofOrderwith@ManyToOne(optional = false)back-reference. Product snapshot decouples order history from future price changes.OrderStatusenum:PENDING,CONFIRMED,CANCELLED.- Migration
V14__evolve_orders_domain.sql: addsorder_number,status,total_amounttoorders; makescustomer_id/product_idnullable; createsorder_itemstable; backfills oneOrderItemper historical order using the product snapshot; backfillstotal_amountfrom the legacytotalcolumn; generatesORD-HIST-000001-style order numbers for historical rows. - Migration
V15__make_orders_total_legacy_nullable.sql: drops theNOT NULLconstraint on the legacytotal DOUBLE PRECISIONcolumn, which V14 stopped mapping in theOrderentity. The column is kept for schema-level backward compatibility but is no longer written by Hibernate. - All monetary amounts are
BigDecimalmapped toNUMERIC(12,2).totalAmount = unitPrice * quantitycomputed inOrderServiceImplusingBigDecimal.multiply, never via floating-point arithmetic.
OrderResponse(one order) embedsOrderCustomerResponseand the fullProductResponse, plusstatus(String),order_number,total_amount(BigDecimal), anditems(List<OrderItemResponse>). Two read paths:findByIdWithDetails(entity withJOIN FETCHon items, used for detail/create/update) andfindAllProjected(17-field JPQL constructor-expression projection, used for the paginated list - no N+1).CustomerResponsecarriesproducts(oneOrderedProductResponseper order) andtotal(BigDecimal sum). Loaded with a singlefindAllProjectedByCustomerIds(INon the page's customer ids) for both the list and the detail.GET /api/v1/ordersgroups by customer (CustomerOrdersResponse), paginated viafindCustomersWithOrders.OrderControllerreturnsResponseEntity<ApiResponse<T>>; snake_case JSON fields via@JsonProperty.
| Method | URL | Description |
|---|---|---|
| GET | /api/v1/orders |
Orders grouped by customer (quantity and total per order, overall total). Paginated by customer, filterable by customerId/productId |
| GET | /api/v1/orders/{id} |
Order detail with items |
| POST | /api/v1/orders |
Create an order (totalAmount and orderNumber computed automatically) |
| PUT | /api/v1/orders/{id} |
Update an order (replaces items, recomputes total) |
| DELETE | /api/v1/orders/{id} |
Delete an order |
| GET | /api/v1/customers/{id}/orders |
Orders for a given customer |
-
OrderStatusenum (PENDING,CONFIRMED,CANCELLED) -
OrderItementity with product snapshot (name + unit price at order time) -
Orderentity evolved:totalAmount(BigDecimal),orderNumber,status,items(cascade + orphanRemoval) - Migrations
V14(multi-product schema + backfill) andV15(legacytotalcolumn nullable) -
OrderItemResponseDTO,OrderItemMapper -
OrderResponseupdated withstatus,total_amount,order_number,items -
OrderCreatedEventenriched withtotalAmountandorderNumber -
OrderRepository: updated projections (17 fields),findByIdWithDetailswithJOIN FETCHon items,existsByCustomerId,existsByProductId,findByCustomerId -
OrderServiceImpl:create/updatecompute BigDecimal subtotal, generateorderNumber, buildOrderItembefore save -
OrderMapper:toResponse(Order)with status enum-to-String expression; manualtoResponse(OrderProjection)overload;toOrderedProductshelper;OrderItemMapperviauses -
CustomerResponsereturns the customer's orders and their total on both the list and the detail - Unit tests, repository tests (including
existsByCustomerId,existsByProductId,findByCustomerId), controller tests, mapper tests
AppUserentity (id, username, email, hashed password, roles)Roleenum (ADMIN,USER)- Migration
V2__init_users_and_roles.sql
| Method | URL | Description | Access |
|---|---|---|---|
| POST | /api/v1/auth/register |
Sign up | Public |
| POST | /api/v1/auth/login |
Sign in, returns a JWT | Public |
| GET | /api/v1/auth/me |
Current user profile | Authenticated |
| Resource | GET | POST/PUT/DELETE |
|---|---|---|
| categories, products | Public | ADMIN |
| customers, orders | Authenticated | ADMIN |
-
AppUser,Role,AppUserRepository -
JwtService(generation, validation, claims extraction) -
JwtAuthFilter(OncePerRequestFilter) -
UserDetailsServiceImpl -
SecurityConfig(SecurityFilterChain, BCryptPasswordEncoder, per-endpoint authorization rules, CSRF disabled for a stateless API,STATELESSsession) -
AuthServiceinterface andAuthServiceImplimplementation (inservice/impl),AuthController(register, login, me) - Custom 401/403 error handling (
AuthenticationEntryPoint,AccessDeniedHandler) - Swagger updated to support the "Authorize" button (Bearer token)
- Integration tests with
spring-security-test(@WithMockUser, allowed/denied access tests) -
AuthControllerreturnsResponseEntity<ApiResponse<T>>;AuthResponse.tokenTypeexposed in JSON astoken_typevia@JsonProperty(the other auth DTO fields,username/email/password/token, are single words already identical in both conventions)
Fine-grained access control: replaces the Role enum from feature/auth with a full JPA entity hierarchy (Role, Permission), CRUD endpoints for both, and method-level security via @PreAuthorize + a custom PermissionEvaluator.
Permissionentity (id,resource,action) - migrationV5Roleentity (id,name) with a@ManyToManytoPermissionrole_permissionjoin table
All endpoints are ADMIN-only (@PreAuthorize("hasRole('ADMIN')") at class level).
| Method | URL | Description |
|---|---|---|
| GET | /api/v1/permissions |
Paginated list of permissions |
| POST | /api/v1/permissions |
Create a permission |
| DELETE | /api/v1/permissions/{id} |
Delete a permission |
| GET | /api/v1/roles |
Paginated list of roles (with permissions) |
| POST | /api/v1/roles |
Create a role |
| PUT | /api/v1/roles/{id} |
Update a role name |
| DELETE | /api/v1/roles/{id} |
Delete a role |
| PATCH | /api/v1/roles/{id}/permissions |
Add and/or remove one or several permissions on a role, body {"add": [1, 2], "remove": [3]} |
-
Permissionentity andPermissionRepository -
Roleentity (JPA, replaces enum) andRoleRepositorywith@EntityGraphon paginatedfindAllto avoid N+1 on permissions - Migration
V5__roles_permissions.sql - DTOs
PermissionRequest/PermissionResponse,RoleRequest/RoleResponse -
PermissionMapper,RoleMapper -
PermissionService/PermissionServiceImplandRoleService/RoleServiceImpl -
PermissionControllerandRoleController(ADMIN-only) -
MethodSecurityConfig(@EnableMethodSecurity, staticMethodSecurityExpressionHandlerbean to avoid circular dependency) -
CustomPermissionEvaluator(PermissionEvaluator): evaluateshasPermission('RESOURCE', 'ACTION')againstPERMISSION_RESOURCE:ACTIONauthorities stored on the user - Service, repository, and controller tests
Token lifecycle management for account activation and password reset, plus async email delivery and scheduled cleanup.
ActivationTokenentity (id,user,token,createdAt,expiresAt,validatedAt) - migrationV6; 24-hour TTL;validatedAtmarks a used token (not deleted, auditable);findByTokencarriesPESSIMISTIC_WRITElock to prevent double-use racesBlacklistedTokenentity (id,user,token,jti,blacklistedAt,createdAt,expiresAt,validatedAt) for JWT revocation; revocation check viaexistsByJti(no lock needed, read-only)PasswordResetTokenentity (id,user,token,type,expiryDate) - 1-hour TTL; consumed by deletion (single-use: token is deleted before expiry is checked, so it is never reusable even if validation fails)
-
ActivationToken,BlacklistedToken,PasswordResetTokenentities and repositories (packageentity/token,repository) - Migration
V6__init_token_tables.sql(activation_tokens, password_reset_tokens, blacklisted_tokens with FK to app_users, indexes on user_id) -
SecureTokenGenerator(@Component,SecureRandom, 32 bytes Base64 URL-safe without padding) -
EmailServiceinterface andEmailServiceImpl(@Async("emailTaskExecutor")withJavaMailSender; uses executor fromAsyncConfiginfeature/core-architecture;app.base-urlproperty for link generation) -
ActivationTokenService/ActivationTokenServiceImpl,BlacklistedTokenService/BlacklistedTokenServiceImpl,PasswordResetTokenService/PasswordResetTokenServiceImpl -
TokenCleanupScheduler(@Scheduled(cron = "0 0 3 * * *")daily at 3 AM; three separate@Transactionalmethods, one per table; usesSchedulingConfigfromfeature/core-architecture) -
InvalidTokenExceptionhandler already present inGlobalExceptionHandler(wired byfeature/core-architecture) - MailHog service added to
docker-compose.yml;application-dev.ymlpoints tolocalhost:1025;application-prod.ymlreadsMAIL_HOST/MAIL_PORT/MAIL_USERNAME/MAIL_PASSWORDfrom env;.env.exampleupdated withMAIL_*andAPP_BASE_URL - Unit tests:
ActivationTokenServiceImplTest,BlacklistedTokenServiceImplTest,PasswordResetTokenServiceImplTest,EmailServiceImplTest,SecureTokenGeneratorTest,TokenCleanupSchedulerTest - Repository tests (Testcontainers):
ActivationTokenRepositoryTest,BlacklistedTokenRepositoryTest,PasswordResetTokenRepositoryTest - Fixed
@ActiveProfiles("test")on all three@SpringBootTestfull-context classes (RepositoryAuditAspectTest,SpringBootTutorialApplicationTests,SecurityAuthorizationTest) soapplication-test.yml(which stubsspring.mail.host) is loaded andJavaMailSenderis auto-configured -
JwtService: addedjticlaim (random UUID per token via.id(UUID.randomUUID().toString())),extractJti(String token), andextractExpiration(String token); removedisTokenValid()(replaced byJwtExceptionin filter + blacklist check) -
AuthService.logout(String rawToken)contract added to the interface -
AuthServiceImpl.logout(): extracts jti/username/expiration from token, loadsAppUser, delegates toBlacklistedTokenService.blacklist() -
AuthController:POST /api/v1/auth/logoutstripsAuthorization: Bearer <token>header and callsauthService.logout() -
JwtAuthFilter: injectsBlacklistedTokenService; checksisBlacklisted(jti)before populating theSecurityContext; catchesDataAccessExceptionalongsideJwtExceptionfor fail-open behaviour on DB outages - Tests:
JwtServiceTestrewritten for jti model;AuthServiceImplTestextended with@Mock BlacklistedTokenService+ twologout()tests;AuthControllerTestgains_08_/_09_forPOST /logout;SecurityAuthorizationTest._16_exercises the full blacklist lifecycle (login -> GET 200 -> logout -> GET 401); all@WebMvcTestslices updated with@MockitoBean BlacklistedTokenService
Admin-facing user management: list, view, activate/deactivate accounts, assign roles; plus account activation and password-reset flows driven by email tokens.
AppUsergains a@ManyToManywithRole(entity) viarole_userjoin table, migrationV7
| Method | URL | Description | Access |
|---|---|---|---|
| GET | /api/v1/users |
Paginated list of users | ADMIN |
| GET | /api/v1/users/{id} |
User detail | ADMIN |
| PATCH | /api/v1/users/{id}/roles |
Add and/or remove one or several roles on a user, body {"add": [1, 2], "remove": [3]} |
ADMIN |
| DELETE | /api/v1/users/{id} |
Delete a user | ADMIN |
| GET | /api/v1/auth/activate |
Activate account with token | Public |
| POST | /api/v1/auth/forgot-password |
Request a password-reset email | Public |
| POST | /api/v1/auth/reset-password |
Reset password with token | Public |
- Migration
V7__role_user.sql(role_userjoin table, seeds ADMIN/USER roles, migrates enum data) -
AppUserrefactored from@Enumerated Roleto@ManyToMany Set<Role>+boolean enabled -
UserDetailsServiceImplmaps roles toROLE_prefixed authorities, propagatesdisabled(!enabled) -
AppUserRepository.findByUsernameannotated@EntityGraph(attributePaths="roles")to avoidLazyInitializationExceptioninJwtAuthFilter -
AuthServiceImpl.register()setsenabled=false, loads USER role from DB, sends activation email -
UserController(ADMIN-only,@PreAuthorizeat class level) - Account activation flow (register -> activation email ->
GET /auth/activate?token=) - Password-reset flow (forgot-password -> email ->
POST /auth/reset-password) -
UserResponseexposesaccount_lockedfield so the Angular users list can show lock status on initial load - Unit and integration tests (service, repository, controller, security authorization)
Persistent shopping cart: one cart per authenticated user, lazily created on first add.
Cartentity:@OneToOne(LAZY)toAppUser(unique, ON DELETE CASCADE),@OneToMany(cascade=ALL, orphanRemoval=true)toCartItem. Audited (@CreatedDate/@LastModifiedDate).CartItementity:@ManyToOne(LAZY)toCartand toProduct. Quantity is a positive integer. The composite unique constraintuq_cart_product(cart_id, product_id)ensures each product appears at most once per cart.- Migration
V17__create_cart_tables.sql: createscartsandcart_itemswith FK and unique constraints and two indexes. CartRepositoryuses@EntityGraph(attributePaths = {"items", "items.product"})on both finders to load the full item graph in one query.
CartItemResponse:id,product_id,product_name,unit_price,quantity,subtotal(computed asunitPrice * quantity).CartResponse:id,items,total(sum of item subtotals).- All monetary amounts are
BigDecimal.
| Method | URL | Description | Access |
|---|---|---|---|
| GET | /api/v1/cart |
View the authenticated user's cart | USER |
| POST | /api/v1/cart/items |
Add a product to the cart (increments quantity if already present) | USER |
| PATCH | /api/v1/cart/items/{itemId} |
Update the quantity of a cart item | USER |
| DELETE | /api/v1/cart/items/{itemId} |
Remove one item from the cart | USER |
| DELETE | /api/v1/cart/items |
Clear the entire cart | USER |
- Only active products (
active = true) may be added to the cart (422 if inactive). - Adding the same product twice increments the existing item's quantity rather than creating a duplicate row.
updateItemandremoveItemverify the item belongs to the caller's cart (404 otherwise).- The user is always resolved from
@AuthenticationPrincipal UserDetails, never from the payload.
- Migration
V17__create_cart_tables.sql -
CartandCartItementities -
CartItemRequest,CartItemUpdateRequest,CartItemResponse,CartResponseDTOs -
CartMapperwith computedsubtotalper item andtotalfor the cart -
CartRepositoryandCartItemRepository -
CartServiceinterface andCartServiceImpl -
CartControllerwith 5 endpoints at/api/v1/cart -
SecurityConfigupdated:/api/v1/cart/**requiresROLE_USER - Unit tests (
CartServiceImplTest), controller tests (CartControllerTest), repository tests (CartRepositoryTest)
Converts the authenticated user's cart into a confirmed order in a single atomic transaction.
POST /api/v1/orders(no body) is called by an authenticated user withROLE_USER.- The service loads the user's cart (404 if none exists, 422 if empty).
- For each
CartItem, the product is re-fetched from the database to obtain the current price. The service never trusts any price stored in the cart or supplied by the client. - Each item is validated: 422 if the product is inactive.
- An
Orderis created with oneOrderItemsnapshot per cart line. TheOrder.userFK links to the authenticatedAppUser(noCustomerrecord is required). totalAmountis computed server-side from the re-fetched prices.- The cart items are deleted in the same transaction. If the
Ordersave fails and rolls back, the cart is left untouched. OrderCreatedEventis published after the transaction commits.
Ordergains a nullableuser_idFK toapp_users(migrationV18). Legacy orders created via the old CRUD endpoint keepcustomer_idonly; checkout orders setuser_idonly.CheckoutRequestis an intentionally empty record: the request body carries no data.
| Method | URL | Description | Access |
|---|---|---|---|
| POST | /api/v1/orders |
Checkout: convert cart to order | USER |
The PUT /api/v1/orders/{id} and DELETE /api/v1/orders/{id} endpoints remain for ADMIN-only legacy CRUD.
POST /api/v1/ordersrequiresROLE_USER(changed from ADMIN-only).PUTandDELETEon orders still requireROLE_ADMIN.- The user is always resolved from
@AuthenticationPrincipal UserDetails, never from an HTTP parameter.
- Migration
V18__add_user_id_to_orders.sql -
AppUser userfield added toOrderentity -
CheckoutRequestDTO -
checkout(String username)added toOrderServiceinterface -
checkoutimplemented inOrderServiceImplwith atomic cart-to-order conversion -
OrderController.checkout()replacescreate(@RequestBody OrderRequest) -
deleteAllByCartIdadded toCartItemRepository -
SecurityConfigupdated:POST /api/v1/ordersnow requiresROLE_USER - Unit tests (
OrderServiceImplTest+5 checkout cases), controller tests (OrderControllerTestupdated)
Post-commit email notifications sent after a successful checkout. The order is already durable when these emails are sent; an SMTP failure logs an error but never affects the order or the HTTP response returned to the client.
OrderServiceImpl.checkout()publishesOrderCreatedEventafter saving the order.OrderCreatedEventListener.onOrderCreated()is annotated with both@TransactionalEventListener(AFTER_COMMIT)and@Async("emailTaskExecutor"):AFTER_COMMITensures the event only fires once the row is durable.@Asyncmoves the work to the email thread pool, decoupling SMTP latency from the event dispatch thread.
- The listener reloads the full order (items +
AppUser) from the database usingOrderRepository.findByIdWithItemsAndUser. Re-loading is necessary because the original transaction is closed and accessing lazy associations on a detached entity would raiseLazyInitializationException. OrderEmailServiceImpl.sendOrderConfirmationsends a plain-text confirmation to the customer's email address (skipped when the order has noAppUser).OrderEmailServiceImpl.sendAdminNotificationsends a plain-text alert to the configured admin address.
| Property | Env variable | Default |
|---|---|---|
app.notifications.admin-email |
APP_NOTIFICATION_ADMIN_EMAIL |
admin@example.com |
app.mail.from |
MAIL_FROM |
noreply@spring-boot-tutorial.com |
The docker-compose.yml runs MailHog on port 1025 (SMTP) and 8025 (web UI).
Point a browser at http://localhost:8025 to see captured emails.
MailException is caught inside each email method and logged at ERROR level.
The exception is never re-thrown. The order is unaffected by an email failure.
NotificationProperties-@ConfigurationProperties(prefix = "app.notifications")OrderEmailService- contract for the two email methodsOrderEmailServiceImpl-@Async("emailTaskExecutor"), plain-text bodies
-
NotificationPropertieswithadminEmailfield -
@EnableConfigurationProperties(NotificationProperties.class)registered inAsyncConfig -
app.notifications.admin-emailadded toapplication.ymland.env.example -
OrderEmailServiceinterface -
OrderEmailServiceImplwith SMTP error handling -
findByIdWithItemsAndUseradded toOrderRepository(LEFT JOIN FETCH, works for checkout and legacy orders) -
OrderCreatedEventListenerextended with@Async+ email calls -
OrderEmailServiceImplTest(3 cases: confirmation, admin notification, SMTP exception swallowed) -
OrderCreatedEventListenerTest(2 cases: with user, without user)
Role-based access control on order endpoints and status lifecycle management.
A ROLE_USER sees only their own orders; a ROLE_ADMIN sees all orders and
can update statuses. Ownership checks live in the service layer, never only in
the controller.
| Endpoint | ROLE_USER | ROLE_ADMIN | Unauthenticated |
|---|---|---|---|
GET /api/v1/orders |
Own orders only | All orders | 401 |
GET /api/v1/orders/{id} |
Own order or 404 | Any order | 401 |
POST /api/v1/orders (checkout) |
Allowed | Allowed | 401 |
PATCH /api/v1/orders/{id}/status |
403 | Allowed | 401 |
PUT /api/v1/orders/{id} |
403 | Allowed | 401 |
DELETE /api/v1/orders/{id} |
403 | Allowed | 401 |
GET /api/v1/cart/** |
Allowed | 403 | 401 |
When a ROLE_USER requests an order that belongs to another user, the API
returns 404, not 403. Returning 403 would reveal that the resource exists;
404 is the correct response to avoid leaking ownership information.
Only a ROLE_ADMIN may change an order's status. Allowed transitions:
| From | To | Result |
|---|---|---|
PENDING |
CONFIRMED |
200 |
PENDING |
CANCELLED |
200 |
CONFIRMED |
CANCELLED |
200 |
| Any other pair | - | 422 Unprocessable Entity |
OrderStatusUpdateRequest- DTO forPATCH /{id}/status, carries@NotNull OrderStatusOrderAuthorizationTest- Testcontainers integration test with 3 actors (userA, userB, admin)
-
OrderStatusUpdateRequestDTO -
findByUserId(EntityGraph on items + items.product) inOrderRepository -
findByIdAndUserId(JOIN FETCH items, filters by user) inOrderRepository -
OrderService.findAll(String username, boolean isAdmin, Pageable)replaces oldfindAll(Long, Long, Pageable) -
OrderService.findById(Long id, String username, boolean isAdmin)replaces oldfindById(Long) -
OrderService.updateStatus(Long id, OrderStatus)with transition validation -
OrderServiceImplauthorization logic (empty page on user-not-found for list) -
OrderControllerrewritten with@AuthenticationPrincipal,@PreAuthorizeon status/update/delete -
SecurityConfigupdated with explicit GET/POST/PATCH/PUT/DELETE rules for/api/v1/orders/** -
OrderControllerTestupdated (12 cases includingupdateStatushappy/error paths) -
OrderAuthorizationTest(8 cases: ownership, admin access, status transitions, 401)
Final integration branch combining feature/order-authorization (the main chain)
and feature/product-images (independent image management branch).
The goal of this branch is to verify that the two independent e-commerce lines
compile and test together cleanly before they are merged into develop.
| File | Conflict | Resolution |
|---|---|---|
application.yml |
app.notifications block vs app.storage block |
Both sections kept under the same app: root |
.env.example |
APP_NOTIFICATION_ADMIN_EMAIL vs APP_STORAGE_UPLOAD_DIR |
Both variables kept |
ProductServiceImpl.java |
OrderRepository (delete guard) vs ProductImageRepository/ProductImageMapper (image loading) |
All three dependencies kept |
ProductControllerTest.java |
Different @MockitoBean sets |
All four mocks kept: JwtService, UserDetailsService, BlacklistedTokenService, ProductImageService |
ProductServiceCacheTest.java |
OrderRepository mock vs ProductImageRepository/ProductImageMapper mocks |
All three mocks kept |
ProductServiceImplTest.java |
OrderRepository mock vs image mocks |
All three mocks kept |
OrderServiceImpl.checkout() did not clear the cart after checkout. Root cause:
cartItemRepository.deleteAllByCartId(cart.getId()) was called while the Cart entity
was managed in the Hibernate persistence context with its items collection still populated.
Cart.items has cascade = CascadeType.ALL, orphanRemoval = true: at flush time, the
cascade PERSIST from the managed Cart re-inserted the rows that the repository delete
had just removed. Fixed by replacing the repository call with cart.getItems().clear(),
which uses the orphan-removal mechanism correctly and avoids the cascade conflict.
Three test classes used the 7-argument ProductResponse constructor after the merge
introduced an 8th field (images): CustomerControllerTest, OrderControllerTest,
OrderServiceImplTest. Fixed by adding List.of() as the 8th argument in each class.
OrderMapper.toResponse(OrderProjection) used the same 7-argument constructor.
Fixed by passing List.of() for the images field (projections carry no image data).
EcommerceIntegrationTest covers the full buyer flow with a real PostgreSQL database
(Testcontainers) and the real security filter chain:
- Public catalogue visible without authentication
- Add a product to the cart
- View cart, extract cart item id
- Update item quantity
- Checkout - order created (
PENDING), cart emptied; item name, quantity, and total asserted - Verify cart is empty after checkout
- User sees their own order in the list
- User can read their own order detail (status =
PENDING) - Admin promotes order to
CONFIRMED - User sees the updated status
- A different user gets 404 on the first user's order
- Create branch from
feature/order-authorization - Merge
feature/product-images, resolve 6 conflicts - Fix
OrderMapper.toResponse(OrderProjection): add missing 8thimagesarg - Fix
CustomerControllerTest,OrderControllerTest,OrderServiceImplTest: add missing 8thimagesarg - Fix
OrderServiceImpl.checkout(): replacecartItemRepository.deleteAllByCartIdwithcart.getItems().clear() - Add
APP_NOTIFICATION_ADMIN_EMAILandAPP_STORAGE_UPLOAD_DIRtodocker-compose.yml; add uploads volume - Add
EcommerceIntegrationTest(11-step end-to-end scenario) - Code review (no blocking findings)
- 454/454 tests green
feature/core-architecture→ Pull Request todevelopfeature/products(depends oncore-architecture) → Pull Request todevelopfeature/customers→ Pull Request todevelopfeature/orders(depends onproductsandcustomers) → Pull Request todevelopfeature/auth(secures everything) → Pull Request todevelopfeature/roles-permissions(fine-grained RBAC) → Pull Request todevelopfeature/token-management(token lifecycle, async email, scheduled cleanup) → Pull Request todevelopfeature/user-management(admin user CRUD, activation/reset flows) → Pull Request todevelopfeature/product-images(fromfeature/productsHEAD — independent of the auth chain) — no PR, merged intofeature/integrationonlyfeature/shopping-cart(fromfeature/user-management, mergesfeature/orders) — no PR, merged into next branchfeature/order-checkout(fromfeature/shopping-cart) — no PR, merged into next branchfeature/order-notifications(fromfeature/order-checkout) — no PR, merged into next branchfeature/order-authorization(fromfeature/order-notifications) — no PR, merged into next branchfeature/integration(fromfeature/order-authorization, mergesfeature/product-images) → single Pull Request todevelopfor the entire e-commerce chaindevelop→masteronce everything is tested and validated
- Root package:
com.edgareldy.springboottutorial - DTOs: Java
recordrather than classes (immutability, less boilerplate) - No business logic in controllers: delegate to the service layer only
- Contract/implementation services: the interface (
XxxService) lives at the root ofservice/, its implementation (XxxServiceImpl) lives inservice/impl/. Controllers and tests only depend on the interface (injected by interface type), never directly on the implementation. - Any service method that writes to the database is annotated
@Transactional(on the implementation) - Every controller returns a
ResponseEntity<ApiResponse<T>>(see Standard response format), includingGlobalExceptionHandlerfor errors - DTO fields are exposed in JSON as snake_case via
@JsonPropertyon each record component, kept camelCase in Java so mappers and services stay idiomatic - List responses are always paginated (
Page<T>→PageResponse<T>DTO) - Endpoint names are plural,
kebab-casewhen composed - Every endpoint documented with
@Operation(summary = "...") - All REST endpoints are versioned under the
/api/v1prefix (e.g./api/v1/categories), so the API can introduce a breaking/api/v2later without touching existing clients - Test naming convention: every test method is named
_NN_Should<Outcome>_When<Condition>, whereNNis a two-digit sequence number with a leading zero, restarting at_01_in each test class and following the order of the methods in the source (e.g._01_ShouldReturnCategory_WhenCategoryExists,_02_ShouldReturnEmpty_WhenCategoryDoesNotExist). This applies to every kind of test (unit, repository, controller, integration, parameterized). No other style (shouldX(),testX(),givenX_whenY_thenZ()) is accepted.
- Layered architecture (controller / service / repository)
- Spring Data JPA: relations, derived queries,
@Query, pagination, sorting, projections - DTOs and mapping (MapStruct)
- Validation (Bean Validation)
- Centralized exception handling (
ProblemDetail, RFC 7807) - Transactions (
@Transactional) - Optimistic locking (
@Version) - Dynamic queries (
Specification/JpaSpecificationExecutor) - Native JPA auditing (
@CreatedDate/@LastModifiedDate) - Schema migrations (Flyway)
- API documentation (OpenAPI / Swagger UI)
- Observability (Actuator, including a custom endpoint; structured logging)
- Security (Spring Security, JWT, role-based authorization)
- Method-level security (
@PreAuthorize,@EnableMethodSecurity, customPermissionEvaluator) - Async processing (
@Async,@EnableAsync,ThreadPoolTaskExecutor) - Scheduled tasks (
@Scheduled,@EnableScheduling) - Email sending (
JavaMailSender, MailHog for local testing) - Testing (unit, integration, Testcontainers)
- Multi-environment configuration (Spring profiles)
@ConfigurationProperties- Application cache (
@Cacheable) - Data seeding (
CommandLineRunner) - Application events (
ApplicationEventPublisher) - Aspect-oriented programming (Spring AOP:
@Around,@Before,@After,@AfterReturning,@AfterThrowing) - Local development tooling (Spring Boot DevTools)
- Containerization (Docker, docker-compose)
- Continuous integration (GitHub Actions)
- File upload (
MultipartFile,FileStorageService, disk storage with configurable path) - Persistent shopping cart (entity-backed cart tied to authenticated user)
- Atomic checkout (multi-entity transactional write: cart drain + order creation)
- Role-based data ownership (
@AuthenticationPrincipal, users see only their own orders)
- Clone the repository and check out
develop - Create/checkout the
feature/core-architecturebranch and follow its task checklist - Continue with
feature/products,feature/customers,feature/orders,feature/auth,feature/roles-permissions,feature/token-management,feature/user-management,feature/product-images,feature/shopping-cart,feature/order-checkout,feature/order-notifications,feature/order-authorization,feature/integrationin that order - Open a Pull Request to
developat the end of each branch - Copy
.env.exampleto.envand fill in the required variables - Run the project with
docker-compose up, then open Swagger UI athttp://localhost:8080/swagger-ui.html - MailHog UI is available at
http://localhost:8025to inspect outgoing emails in local dev
Adds image management to the product catalogue. Created from feature/products HEAD, independent of the main authentication/user chain.
| Method | URL | Description |
|---|---|---|
| POST | /api/v1/products/{id}/images |
Upload an image for a product (multipart/form-data, ROLE_ADMIN) |
| DELETE | /api/v1/products/{id}/images/{imageId} |
Delete a product image (ROLE_ADMIN) |
-
ProductImageentity (product_id,filename,url,sort_order) - Flyway migration V15
-
FileStorageServiceinterface +LocalFileStorageServiceimpl (stores files under${app.storage.upload-dir}) -
StoragePropertiesrecord (@ConfigurationProperties(prefix = "app.storage"),uploadDir,maxFileSizeMb) -
POST /api/v1/products/{id}/images: receivesMultipartFile, delegates toFileStorageService, persistsProductImage -
DELETE /api/v1/products/{id}/images/{imageId}: deletes record and removes file from disk -
ProductResponsegainsList<ProductImageResponse> images(always populated) - Unit tests for
FileStorageService(happy path, size limit, unsupported type) - MockMvc controller tests
- Branch is independent of the auth chain (
feature/auththroughfeature/user-management). It is merged intofeature/integrationat the end, not cascaded through the main chain. StoragePropertiesis arecordwith@ConfigurationProperties, consistent withJwtPropertiesfromfeature/auth.- File type validation rejects anything that is not
image/jpeg,image/pngorimage/webp.
Persistent shopping cart backed by JPA entities, one cart per authenticated user.
| Method | URL | Description |
|---|---|---|
| GET | /api/v1/cart |
Get the current user's cart (creates it if absent) |
| POST | /api/v1/cart/items |
Add a product to the cart |
| PATCH | /api/v1/cart/items/{itemId} |
Update item quantity |
| DELETE | /api/v1/cart/items/{itemId} |
Remove a single item |
| DELETE | /api/v1/cart |
Clear the entire cart |
-
Cartentity (user_idFK →app_users, timestamps via@CreatedDate/@LastModifiedDate) -
CartItementity (cart_id,product_id,quantity) - Flyway migration V16
-
CartServiceinterface +CartServiceImpl - All endpoints require ROLE_USER; user resolved via
@AuthenticationPrincipal UserDetails -
CartResponseDTO:id,List<CartItemResponse> items,total(sum computed server-side) -
AddCartItemRequest/UpdateCartItemRequestDTOs with validation - Unit tests (Mockito) + MockMvc controller tests
- Cart is created lazily on first
GET /api/v1/cartfor a user who has none. totalis computed by the service layer from live product prices, never stored.- Branch starts from
feature/user-management(needsAppUser) and mergesfeature/orders(needsOrderschema context for checkout).
Atomic cart-to-order conversion: a single POST /api/v1/orders drains the cart and creates a fully populated Order with OrderItem lines.
| Method | URL | Description |
|---|---|---|
| POST | /api/v1/orders |
Checkout: convert cart to order (ROLE_USER) |
| GET | /api/v1/orders |
List the current user's orders, paginated |
| GET | /api/v1/orders/{id} |
Order detail with items |
-
OrderItementity (order_id,product_id,quantity,unit_pricesnapshot) -
Orderrefactor: adduser_id,order_number(UUID),statusenum (PENDING/CONFIRMED/SHIPPED/DELIVERED/CANCELLED),total_amount NUMERIC(12,2) - Flyway migration V14 (new columns,
order_itemstable, historical data migration) -
CheckoutServiceorOrderService.checkout(UserDetails):@Transactional, loads cart, createsOrder+OrderItemlines (price snapshot), clears cart -
CheckoutRequestDTO (optionalnotesfield) -
OrderResponseDTO:id,orderNumber,status,totalAmount,List<OrderItemResponse> items,createdAt - Service unit tests (atomic write, empty-cart 422, out-of-stock 422)
- MockMvc controller tests
- Price snapshot:
OrderItem.unitPricecapturesProduct.unitPriceat checkout time so future price changes do not alter historical orders. - Empty cart returns 422 (
BusinessRuleException), not 400. order_numberis a UUID generated by the service, never supplied by the client.
Sends an email to the user and to the admin when an order is placed, using the existing Spring Mail infrastructure (JavaMailSender, MailHog on dev).
-
NotificationPropertiesrecord (@ConfigurationProperties(prefix = "app.notifications"),adminEmail) -
OrderEmailServiceinterface +OrderEmailServiceImpl:sendOrderConfirmationToUser(Order)andsendOrderAlertToAdmin(Order), both@Async("emailTaskExecutor") -
OrderCreatedEventListenerupdated to callOrderEmailServiceafter commit (@TransactionalEventListener(AFTER_COMMIT)) - Email templates (plain text, inline in the service or as
src/main/resources/templates/*.txt) - Unit tests (mock
JavaMailSender, verifyMimeMessagerecipients)
- Same async executor as
feature/token-management(emailTaskExecutordefined inAsyncConfig). NotificationProperties.adminEmailis supplied viaAPP_NOTIFICATION_ADMIN_EMAILenv var; added to.env.example.
Restricts order visibility and status mutation by role.
| Method | URL | Description |
|---|---|---|
| GET | /api/v1/orders |
ROLE_USER sees only their own orders; ROLE_ADMIN sees all |
| GET | /api/v1/orders/{id} |
Returns 404 (not 403) if the order belongs to another user |
| PATCH | /api/v1/orders/{id}/status |
Update order status (ROLE_ADMIN only) |
-
SecurityConfigrules:GET /api/v1/orders/**→ authenticated; ownership enforced in service -
OrderService.findAll(UserDetails, Pageable)andfindById(Long, UserDetails): admin bypasses ownership check, user gets 404 on others' orders -
PATCH /api/v1/orders/{id}/status→@PreAuthorize("hasRole('ADMIN')"), bodyOrderStatusUpdateRequestwith@NotNull OrderStatus status -
OrderStatusUpdateRequestDTO -
@SpringBootTestauthorization tests: user isolation, admin override, status update access
- 404 instead of 403 on ownership mismatch: returning 403 leaks the existence of the resource; a consistent 404 is safer.
- Status transitions are not validated (any admin can set any status): validation logic can be added later without breaking the API.
Final integration branch: merges feature/product-images into the main chain and validates the complete e-commerce flow end-to-end.
- Merge
feature/product-images(resolve conflicts onProductResponse,ProductController,application.yml) -
EcommerceIntegrationTest(@SpringBootTest+ Testcontainers): register, login, browse catalogue, upload image (admin), add items to cart, checkout, verify order, admin status update, user isolation (user A cannot see user B's order) -
docker-compose.ymlupdated: volume./uploads:/app/uploads, env varsAPP_STORAGE_UPLOAD_DIR,APP_NOTIFICATION_ADMIN_EMAIL -
.env.exampleupdated with all new variables - README updated with the full e-commerce endpoint table and configuration instructions
- This is the only PR to
developfor the entire e-commerce extension chain (phases 3–8); the intermediate branches (shopping-cartthroughorder-authorization) are merged feature-to-feature. feature/product-imagesis the only side branch and is merged here rather than through the main chain.