DEV Community

Devanshu Biswas
Devanshu Biswas

Posted on

OrderHub Day 4: Bean Validation + Clean DTOs (Spring Boot)

OrderHub Day 4: never trust the client. Today the backend gets proper Bean Validation — bad requests are rejected at the edge with a clear 400, long before they reach the business logic. And it's all declarative.

Try the validating form (see the 400 body): https://dev48v.infy.uk/orderhub/day4-validation.html

Three DTOs, three jobs

A common beginner mistake is using one class everywhere. OrderHub keeps them separate:

  • Request DTO (CreateOrderRequest) — what the client sends, and where validation lives.
  • Domain/Entity (Order) — the internal model.
  • Response DTO (OrderResponse) — what the API returns, so internal fields never leak.

Validation is just annotations

public record CreateOrderRequest(
    @NotBlank @Size(max = 120) @CleanText String customer,
    @NotBlank @Size(max = 200) @CleanText String item,
    @Min(1) @Max(1000) int quantity) {}
Enter fullscreen mode Exit fullscreen mode

Add @Valid @RequestBody on the controller and Spring checks every rule before your method runs. Break one and it throws MethodArgumentNotValidException.

A custom constraint + clean errors

@CleanText is a custom ConstraintValidator (rejects blank-after-trim + a small blocklist) — you can write your own rules, not just the built-ins. A @RestControllerAdvice turns validation failures into a tidy 400 with a field→message map. (Day 5 upgrades this to full RFC-7807 ProblemDetail.)

🔨 Full walkthrough (constraints → @valid → custom validator → 400 handler) on the page: https://dev48v.infy.uk/orderhub/day4-validation.html

OrderHub — a production-grade Spring Boot backend, one feature a day.
🌐 https://dev48v.infy.uk · Code: https://github.com/dev48v/order-hub-from-zero

Top comments (0)