Skip to main content

Posts

Showing posts with the label Hexagonal Architecture

Where to Place @Transactional in Hexagonal Architecture: Use Cases vs Adapters

  Migrating to Hexagonal Architecture (Ports and Adapters) promises decoupled code and domain-centric design. However, it introduces a specific friction point for Spring Boot developers:   Transaction Management. In a traditional Layered Architecture, placing  @Transactional  on the Service layer is muscle memory. In Hexagonal, the "Service" is split into Use Cases, Input Ports, and Application Services. If you misplace the transaction boundary, you face two critical failures: the dreaded  LazyInitializationException  during DTO mapping, or worse, data corruption due to partial commits when a business operation spans multiple driven adapters. This guide defines strictly where  @Transactional  belongs in a robust Hexagonal setup, why it belongs there, and how to implement it using Java 21 and Spring Boot 3. The Root Cause: Why Boundaries Break To understand where to put the annotation, we must understand what Spring and Hibernate are doing under th...

Handling Database Transactions in Hexagonal Architecture Without Leaking Abstractions

  The Blocker: The "Transactional" Annotation Trap You have meticulously designed your Hexagonal Architecture (Ports & Adapters). You have a pristine Domain layer and a segregated Application (Use Case) layer. You have stripped away all frameworks from your core. Then, you write a Use Case that requires atomicity: Deduct inventory. Charge the credit card. Save the order. If any step fails, all must fail. The instinct is to reach for a framework-specific annotation (like Spring’s  @Transactional  or NestJS interceptors) and slap it on the Use Case method. Stop. The moment you import  org.springframework.transaction.annotation.Transactional  (or similar) into your Use Case layer, you have violated the  Dependency Rule . Your inner circle now depends on a framework mechanism living in the outer circle. You are no longer framework-agnostic. If you swap the persistence adapter or the framework, your business logic breaks. The Root Cause: Mixing Business Boun...