Skip to main content

Infrastructure Layer: JPA and Redis in Clean Architecture

The infrastructure layer implements the ports of domain/application through adapters: JPA for persistence, Redis for caching, WebClient for external services.

What do you think about this article?

Infrastructure Layer: JPA and Redis in Clean Architecture
Clean ArchitecturePhotos:RDNE Stock projectPexels

At a Glance

The infrastructure layer implements the ports of domain/application through adapters: JPA for persistence, Redis for caching, WebClient for external services.

The infrastructure layer is the technical heart of Clean Architecture: it implements the ports defined by domain/application through concrete adapters. In Spring Boot 3.4, this means writing JPA adapters that map database entities to domain models, configuring Redis for caching with @Cacheable, and consuming external services via WebClient, always maintaining the dependency arrow pointing toward the domain. This article shows you how to implement this layer in production with PostgreSQL 16 and Redis Stack 7, which patterns to avoid, and how to test adapters in isolation.

What Is the Infrastructure Layer in Clean Architecture

The infrastructure layer (Layer 3) is the layer that implements the **ports** (interfaces) defined by the domain (Layer 1) and application (Layer 2). It is where technical complexity enters: database, cache, external APIs, file system, SMTP. The only rule is: the domain and application must not know it exists.

Dependency always flows inward: infrastructure depends on application and domain, NEVER the reverse. This means that if tomorrow you decide to change from PostgreSQL to MongoDB, or from Redis to Memcached, you only modify this layer. Your business logic remains unchanged.

Port vs Adapter: The Foundation

A **port** is an interface defined in the domain or application that describes what needs to be done (e.g., "save a user"). An **adapter** is the concrete implementation of that port (e.g., "use JPA and PostgreSQL").


// Domain Layer - Port (pure interface, zero Spring)
public interface UserRepository {
    void save(User user);
    Optional<User> findById(UserId id);
    Optional<User> findByEmail(Email email);
}

// Infrastructure Layer - Adapter (concrete implementation with Spring/JPA)
@Component
public class UserJpaAdapter implements UserRepository {
    private final UserJpaRepository jpaRepository;
    private final UserMapper mapper;

    public UserJpaAdapter(UserJpaRepository jpaRepository, UserMapper mapper) {
        this.jpaRepository = jpaRepository;
        this.mapper = mapper;
    }

    @Override
    public void save(User user) {
        UserJpaEntity entity = mapper.toJpaEntity(user);
        jpaRepository.save(entity);
    }

    @Override
    public Optional<User> findById(UserId id) {
        return jpaRepository.findById(id.value())
            .map(mapper::toDomain);
    }
}
  

JPA Adapter: Entity-to-Domain Mapping

The main challenge of the JPA adapter is mapping JPA entities (annotated with @Entity, @Column) to pure domain models (records, immutable, zero Spring). Use a dedicated mapper to isolate conversion logic.


// Infrastructure: JPA Entity (coupled to Spring/Hibernate)
@Entity
@Table(name = "users")
public class UserJpaEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    private String id;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String hashedPassword;

    @Enumerated(EnumType.STRING)
    private UserRole role;

    @CreationTimestamp
    private ZonedDateTime createdAt;

    @UpdateTimestamp
    private ZonedDateTime updatedAt;

    // getters/setters
}

// Infrastructure: Mapper (bidirectional conversion)
@Component
public class UserMapper {
    public User toDomain(UserJpaEntity entity) {
        return new User(
            new UserId(entity.getId()),
            new Email(entity.getEmail()),
            entity.getHashedPassword(),
            Role.valueOf(entity.getRole().name()),
            entity.getCreatedAt(),
            entity.getUpdatedAt()
        );
    }

    public UserJpaEntity toJpaEntity(User domain) {
        UserJpaEntity entity = new UserJpaEntity();
        entity.setId(domain.id().value());
        entity.setEmail(domain.email().value());
        entity.setHashedPassword(domain.hashedPassword());
        entity.setRole(UserRole.valueOf(domain.role().name()));
        entity.setCreatedAt(domain.createdAt());
        entity.setUpdatedAt(domain.updatedAt());
        return entity;
    }
}
  

Spring Data Repository: The Technical Wrapper

Spring Data JPA provides a generic repository that simplifies CRUD queries. It is an additional layer between the adapter and Hibernate, useful but optional. In our pattern, the JPA repository is an implementation detail, not part of the public interface.


// Infrastructure: Spring Data Interface (internal, not exposed to domain)
@Repository
public interface UserJpaRepository extends JpaRepository<UserJpaEntity, String> {
    Optional<UserJpaEntity> findByEmail(String email);
    List<UserJpaEntity> findByRole(UserRole role);
}

// The adapter uses the JpaRepository internally
@Component
public class UserJpaAdapter implements UserRepository {
    private final UserJpaRepository jpaRepo;
    private final UserMapper mapper;

    @Override
    public Optional<User> findByEmail(Email email) {
        return jpaRepo.findByEmail(email.value())
            .map(mapper::toDomain);
    }
}
  

Redis Caching with @Cacheable

Caching reduces database queries. Spring Cache Abstraction allows you to decorate methods with @Cacheable to store results in Redis. The cache key must be unique and deterministic.


// Infrastructure: Adapter with caching
@Component
public class ArticleJpaAdapter implements ArticleRepository {
    private final ArticleJpaRepository jpaRepo;
    private final ArticleMapper mapper;
    private final CacheManager cacheManager;

    @Cacheable(value = "articles", key = "#id.value()")
    @Override
    public Optional<Article> findById(ArticleId id) {
        return jpaRepo.findById(id.value())
            .map(mapper::toDomain);
    }

    @Override
    public void save(Article article) {
        ArticleJpaEntity entity = mapper.toJpaEntity(article);
        jpaRepo.save(entity);
        // Invalidate the cache
        evictCache(article.id());
    }

    private void evictCache(ArticleId id) {
        Cache cache = cacheManager.getCache("articles");
        if (cache != null) {
            cache.evict(id.value());
        }
    }
}

// Application Configuration
@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory connectionFactory) {
        return new RedisCacheManager.create(connectionFactory);
    }
}
  

WebClient: Consuming External Services

WebClient is Spring Boot's modern HTTP client for communicating with microservices or external APIs. In our pattern, we wrap it in an adapter that implements a port, so the domain never knows about HTTP.


// Domain: Port for external service (no HTTP, pure interface)
public interface RecommendationService {
    List<ArticleId> recommendSimilar(ArticleId id, int limit);
}

// Infrastructure: WebClient Adapter
@Component
public class ExternalRecommendationAdapter implements RecommendationService {
    private final WebClient webClient;
    private final ObjectMapper objectMapper;

    public ExternalRecommendationAdapter(WebClientBuilder builder) {
        this.webClient = builder.baseUrl("http://ml-service:8000/api/v1")
            .build();
        this.objectMapper = new ObjectMapper();
    }

    @Override
    public List<ArticleId> recommendSimilar(ArticleId id, int limit) {
        return webClient.get()
            .uri("/recommend/{id}?limit={limit}", id.value(), limit)
            .retrieve()
            .onStatus(status -> !status.is2xxSuccessful(),
                clientResponse -> Mono.error(
                    new ExternalServiceException("ML service error: " + clientResponse.getStatusCode())
                ))
            .bodyToMono(RecommendationResponse.class)
            .map(RecommendationResponse::toArticleIds)
            .blockOptional()
            .orElseThrow(() -> new ExternalServiceException("No recommendations"));
    }
}
  

Maintaining the Dependency Arrow

The golden rule: infrastructure depends on application and domain, NEVER the reverse. How do we verify this? With ArchUnit, a library that validates architectural constraints at compile-time.


@ArchTest
public static final ArchRule infrastructure_should_depend_on_domain_and_application =
    classes()
        .that()
        .resideInAPackage("..infrastructure..")
        .should()
        .onlyDependOnClassesThat()
        .resideInAnyPackage(
            "..domain..",
            "..application..",
            "..infrastructure..",
            "java..",
            "org.springframework..",
            "javax..",
            "jakarta.."
        )
        .check(new ClassFileImporter().importPackages("dev.federicocalo.portfolio"));

@ArchTest
public static final ArchRule domain_should_not_depend_on_infrastructure =
    classes()
        .that()
        .resideInAPackage("..domain..")
        .should()
        .notDependOnClassesThat()
        .resideInAPackage("..infrastructure..")
        .check(new ClassFileImporter().importPackages("dev.federicocalo.portfolio"));
  

Query Objects: Separating Complex Queries

When JPA queries become complex (joins, sub-selects, aggregations), extract a dedicated QueryObject. It is a pattern that keeps the JpaRepository simple and queries readable.


// Infrastructure: Query Object
@Component
public class ArticleSearchQuery {
    private final EntityManager em;

    public Page<Article> searchByTag(String tag, int page, int size) {
        String jpql = "SELECT a FROM ArticleJpaEntity a " +
                      "JOIN a.tags t " +
                      "WHERE t.name = :tag " +
                      "ORDER BY a.publishedAt DESC";

        Query query = em.createQuery(jpql, ArticleJpaEntity.class);
        query.setParameter("tag", tag);
        query.setFirstResult(page * size);
        query.setMaxResults(size);

        return query.getResultList()
            .stream()
            .map(mapper::toDomain)
            .collect(Collectors.toList());
    }
}
  

Transaction Boundaries in Infrastructure

Transactions should be at the layer where data changes enter: typically the application layer (use case). The infrastructure adapter is "lazy": it executes what the application tells it to.


// Application: Use Case with transaction
@Component
@Transactional
public class PublishArticleUseCase {
    private final ArticleRepository articleRepo;
    private final NotificationService notificationService;

    public void execute(PublishArticleCommand cmd) {
        Article article = Article.create(cmd.title(), cmd.content());
        articleRepo.save(article);
        // Transaction still open
        notificationService.notifySubscribers(article);
        // Commit at method end
    }
}

// Infrastructure: Adapter (no @Transactional)
@Component
public class ArticleJpaAdapter implements ArticleRepository {
    private final ArticleJpaRepository jpaRepo;

    @Override
    public void save(Article article) {
        ArticleJpaEntity entity = mapper.toJpaEntity(article);
        jpaRepo.save(entity); // Transaction managed by application layer
    }
}
  

Anti-Pattern: Domain Depending on JPA

The most common mistake: adding @Entity or @Column directly to the domain model. This couples the domain to Hibernate, making it untestable and hard to change.


// WRONG: domain coupled to JPA
@Entity
@Table(name = "users")
public class User {
    @Id
    private String id;

    @Column(nullable = false)
    private String email;
    // ...
}

// CORRECT: pure domain, zero framework
public record User(
    UserId id,
    Email email,
    String hashedPassword,
    Role role,
    ZonedDateTime createdAt
) {
    public boolean isPasswordValid(String plainPassword) {
        return BCrypt.checkpw(plainPassword, hashedPassword);
    }
}
  

Anti-Pattern: JPA Entities Exposed in DTOs

Returning UserJpaEntity directly in REST API response DTOs exposes the database structure to clients. Always use a mapper from domain model to response DTOs.


// WRONG
@RestController
public class UserController {
    @GetMapping("/{id}")
    public ResponseEntity<UserJpaEntity> getUser(@PathVariable String id) {
        return jpaRepository.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }
}

// CORRECT: domain model + DTO mapper
@RestController
public class UserController {
    private final GetUserUseCase useCase;
    private final UserResponseMapper mapper;

    @GetMapping("/{id}")
    public ResponseEntity<UserResponse> getUser(@PathVariable String id) {
        User domainUser = useCase.execute(new UserId(id));
        return ResponseEntity.ok(mapper.toResponse(domainUser));
    }
}
  

Typical Spring Boot 3.4 Configuration


# application.yml
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/portfolio
    username: ${DB_USER}
    password: ${DB_PASSWORD}
    hikari:
      maximum-pool-size: 20
      minimum-idle: 5
  jpa:
    hibernate:
      ddl-auto: validate  # Use Flyway for migrations
    show-sql: false
    properties:
      hibernate:
        format_sql: true
        use_sql_comments: true
        jdbc.batch_size: 20
        order_inserts: true
        order_updates: true
  cache:
    type: redis
    redis:
      host: localhost
      port: 6379
      time-to-live: 3600000  # 1 hour
  redis:
    timeout: 2000
    jedis:
      pool:
        max-active: 20
        max-idle: 10
  

Testing the Infrastructure Layer

Test adapters in isolation with Testcontainers (real PostgreSQL and Redis). Do not use mocks: we want to verify actual mappings and queries.


@SpringBootTest
@Testcontainers
public class UserJpaAdapterTest {

    @Container
    static PostgreSQLContainer<?> postgres =
        new PostgreSQLContainer<>("postgres:16")
            .withDatabaseName("test_db");

    @Container
    static GenericContainer<?> redis =
        new GenericContainer<>("redis:7")
            .withExposedPorts(6379);

    @Autowired
    private UserJpaAdapter adapter;

    @Test
    void testSaveAndFindById() {
        User user = new User(new UserId("1"), new Email("test@example.com"),
                             "hash", Role.USER, ZonedDateTime.now());
        adapter.save(user);

        Optional<User> found = adapter.findById(new UserId("1"));
        assertThat(found).isPresent();
        assertThat(found.get().email().value()).isEqualTo("test@example.com");
    }
}
  

FAQ

Q: Do I always need to create a mapper? Why not use ModelMapper?

A: Explicit mappers (hand-coded) are preferable because they document the conversion, are easy to debug, and don't have the "magic" of ModelMapper that can be slow in production. For small projects ModelMapper is fine, but in enterprise scale (portfolio has 1500+ files) verbosity is an asset.

Q: Does @Cacheable work well with immutable records?

A: Perfectly. Spring Cache uses the hashCode and equals of the key (in the example, the ArticleId value) to manage the cache. Records are immutable and hashable by default.

Q: If Redis goes down, what happens?

A: With @Cacheable, if Redis is unavailable, Spring ignores caching and calls the method normally (graceful degradation). To monitor failures, add a custom CacheErrorHandler.

Q: Where do I put business validation logic in the JPA adapter?

A: Never in the adapter. Business validation lives in the domain (methods on entity), and technical validation (unique email, length) lives in the database (constraint) or in the use case (application). The adapter is "deaf", it executes orders.

Q: Can I use custom @Query in the JPA adapter?

A: Yes, if the query is simple and scoped. For complex queries (many joins, aggregations), extract a QueryObject. The advantage is that the QueryObject is testable, documented, and reusable.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects