Spring Boot Tutorial

59 posts in this section

CRUD Operations with JpaRepository

You have entities and repositories set up. Now let’s work through every data operation in depth — create, read, update, delete — and the JPA mechanics behind each. Create: save() @Service @RequiredArgsConstructor @Transactional public class OrderService { private final OrderRepository orderRepository; public Order createOrder(CreateOrderRequest request) { Order order = new Order(); order.setCustomerId(request.customerId()); order.setOrderNumber(generateOrderNumber()); order.setStatus(OrderStatus.PENDING); request.items().forEach(itemReq -> { OrderItem item = new OrderItem(); item.setProductId(itemReq.productId()); item.setQuantity(itemReq.quantity()); item.setUnitPrice(itemReq.unitPrice()); order.addItem(item); // manages bidirectional relationship }); return orderRepository.

Continue reading »

Database Migrations with Flyway

Never use spring.jpa.hibernate.ddl-auto=update in production. It’s unpredictable, irreversible, and can corrupt data. Flyway gives you version-controlled, audited, reproducible schema changes. Why Flyway? Every database change runs as a versioned SQL script. Flyway tracks which scripts have run in a flyway_schema_history table. When the app starts: Flyway reads all migration files Checks which have already run (by checking the history table) Runs any new ones, in order If the current state doesn’t match the expected state → fails fast Benefits:

Continue reading »

Dockerizing Spring Boot Applications

Packaging your Spring Boot application as a Docker container is the standard way to deploy it — to Kubernetes, cloud platforms, or any container runtime. This article covers building production-quality images. The Naive Dockerfile (Don’t Use This) FROM eclipse-temurin:21-jdk COPY target/order-service.jar app.jar ENTRYPOINT ["java", "-jar", "app.jar"] Problems: 600MB+ image (JDK, not JRE) No layer caching — every code change rebuilds the whole JAR layer Runs as root (security risk) No health check Layered JARs (Better Cache Utilization) Spring Boot 3 creates layered JARs by default.

Continue reading »

DTOs and Response Shaping

Every beginner makes the same mistake: returning JPA entities directly from REST controllers. This article explains why that’s dangerous, and how to design clean DTOs that make your API stable, secure, and maintainable. Why Not Return Entities Directly? Consider this: @GetMapping("/{id}") public Order getOrder(@PathVariable UUID id) { return orderRepository.findById(id).orElseThrow(); // Entity returned directly } Problems with this: 1. Serialization of lazy-loaded relationships crashes @Entity public class Order { @OneToMany(fetch = FetchType.

Continue reading »

Entity Relationships: @OneToMany, @ManyToOne, @ManyToMany

Relationships are the trickiest part of JPA. A wrong cascade type or a missing mappedBy causes subtle bugs that appear in production. This article covers every relationship type with real examples and the pitfalls to avoid. Relationship Fundamentals JPA relationships can be: Direction: Unidirectional (one side knows about the other) or Bidirectional (both sides know each other) Cardinality: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany Fetch: LAZY (load on access) or EAGER (load immediately) Ownership: The side with the foreign key column is the owner Default fetch types:

Continue reading »

Externalized Configuration with @ConfigurationProperties

@ConfigurationProperties binds external configuration to a typed Java class — replacing scattered @Value annotations with a single, validated, testable object. Why @ConfigurationProperties Over @Value // @Value — scattered, no type safety, no validation @Service public class PaymentService { @Value("${payment.gateway.url}") private String gatewayUrl; @Value("${payment.gateway.timeout:5000}") private int timeoutMs; @Value("${payment.gateway.api-key}") private String apiKey; @Value("${payment.gateway.max-retries:3}") private int maxRetries; } // @ConfigurationProperties — one place, typed, validated @Service public class PaymentService { private final PaymentProperties properties; // all config in one place, injected as a single object } @ConfigurationProperties gives you:

Continue reading »

Full Observability: Prometheus + Grafana + Tempo + Loki

Observability means being able to answer “what’s wrong and why” from the outside — without modifying the code. The three pillars: metrics (what happened), logs (what the code did), and traces (how a request flowed). This article wires them all together. The Stack Spring Boot App ├── Metrics → Micrometer → Prometheus scrape → Grafana dashboards ├── Traces → Micrometer Tracing → OTLP → Tempo → Grafana trace view └── Logs → Logback → Loki4j → Loki → Grafana log explorer All three converge in Grafana — click a metric spike to see the correlated logs and traces for that exact time window.

Continue reading »

Global Exception Handling with @ControllerAdvice and ProblemDetail

Without global exception handling, Spring returns raw stack traces or inconsistent error shapes. This article shows how to centralize all error handling in one place and return structured, RFC 7807-compliant responses. The Problem Without Global Handling Default Spring Boot error responses are inconsistent: // Validation failure (MethodArgumentNotValidException) { "timestamp": "2026-05-03T10:00:00.000+00:00", "status": 400, "error": "Bad Request", "path": "/api/orders" } // Details of which fields failed? Not included. // Custom exception not handled // → 500 Internal Server Error with a stack trace in the body (in dev mode) What clients actually need:

Continue reading »

GraalVM Native Images: Millisecond Startup

A regular Spring Boot application takes 2–10 seconds to start. A GraalVM native image of the same application starts in under 100 milliseconds. For serverless functions, batch jobs, and CLI tools, this is the difference between viable and unusable. What Is a Native Image? GraalVM’s native image compiler performs ahead-of-time (AOT) compilation. Instead of shipping a JAR that the JVM interprets at runtime, you ship a standalone executable that: Contains only the code your application actually uses Has no JVM startup overhead Uses much less memory (no JIT compiler, no class metadata) Starts in milliseconds The tradeoff: compile time increases from seconds to minutes.

Continue reading »

Graceful Shutdown and Production Readiness

An application that starts and serves traffic is not production-ready. Production readiness means it shuts down cleanly, handles spikes, recovers from transient failures, and gives you visibility into what it’s doing. This article covers the operational layer. Graceful Shutdown When Kubernetes terminates a pod, it sends SIGTERM. Without graceful shutdown, in-flight requests are killed mid-execution — users see 500 errors or dropped writes. Enable graceful shutdown: server: shutdown: graceful # wait for in-flight requests to complete spring: lifecycle: timeout-per-shutdown-phase: 30s # max wait before forcing shutdown With this configured, Spring Boot:

Continue reading »