liveBook · Manning

Persistence adapter

As explained in Clean Applications with Hexagonal Architecture

An adapter that implements persistence contracts and translates between domain objects and storage technology.

When a domain aggregate doubles as a database entity, persistence requirements can introduce framework dependencies and mutation paths that bypass domain invariants. A persistence adapter keeps those concerns outside the core: it implements a repository contract and translates between domain objects and the storage technology. section 9.5.1 section 8.6.1

The repository interface belongs to the domain; the adapter depends on that interface, not the reverse. In the module layout, the persistence adapter may depend on the domain, shared kernel, and data framework, but not on other adapters or input and output ports. The assembly module wires the repository implementation into handlers at runtime. section 6.1 section 6.2

Article persistence with JPA

ArticleRepository accepts and returns domain types such as Article and ArticleId. A separate JpaArticle holds primitive fields and satisfies JPA’s construction and mutation requirements. SpringArticleRepository operates on JpaArticle and String, so it is an infrastructure collaborator, not the domain port. JpaArticleRepository implements the port, uses a mapper, and delegates storage operations to Spring Data. section 9.5.1

Listing 9.24 ArticlePersistenceMapper: The two-way translator
@Component
class ArticlePersistenceMapper {
 
  JpaArticle toJpaEntity(final Article article) { #A
    return new JpaArticle(
      article.id().value(),
      article.title().value(),
      article.content().value(),
      article.authorId().value(),
      article.status().name());
  }
 
  Article toDomainEntity(final JpaArticle jpaArticle) { #B
    return Article.reconstitute(
      ArticleId.validateThenCreate(jpaArticle.getId())
        .get(), #C
      Title.validateThenCreate(jpaArticle.getTitle()).get(),
      Content.validateThenCreate(jpaArticle.getContent()).get(),
      AuthorId.validateThenCreate(jpaArticle.getAuthorId()).get(),
      ArticleStatus.valueOf(jpaArticle.getStatus())); #D
  }
 
  ArticleDTO toDTO(final JpaArticle jpaArticle) { #E
    return new ArticleDTO(
      jpaArticle.getId(),
      jpaArticle.getTitle(),
      jpaArticle.getAuthorId(),
      jpaArticle.getStatus());
  }
}

The mapper converts an Article to a JPA entity and reconstitutes an aggregate from stored fields. section 9.5.1

Reconstitution is distinct from creating a new aggregate: the example trusts the database when rehydrating an Article, while reconstructing its value objects from stored fields. A separate persistence model avoids giving JPA setters or a no-argument constructor to the aggregate itself. section 9.5.1

Listing 9.25 JpaArticleRepository: The port implementation
@Adapter #A
@RequiredArgsConstructor
class JpaArticleRepository implements ArticleRepository {
 
  private static final String ORIGIN = "JpaArticleRepository";
  private static final String ENTITY = "Article";
 
  private final SpringArticleRepository springArticleRepository;
  private final ArticlePersistenceMapper mapper;
 
  @Override
  public Either<Error, Void> save(final Article article) {
    try {
      this.springArticleRepository.save(
        this.mapper.toJpaEntity(article));
      return Either.right(null);
    } catch (final DataAccessException e) { #B
      return Either.left(
        new Error.TechnicalError.PersistenceError(
          ORIGIN, "save", e.getMessage()));
      }
  }
 
  @Override
  public Either<Error, Article>
    readById(final ArticleId id) { #C
    return this.springArticleRepository.findById(id.value())
      .<Either<Error, Article>>map(jpa ->
        Either.right(this.mapper.toDomainEntity(jpa)))
      .orElseGet(() -> Either.left(
        new Error.BusinessError.NotFound(
          ORIGIN, ENTITY, id.value()))); #D
  }
 
  @Override
  public Either<Error, ArticleDTO>
    findById(final ArticleId id) { #E
    return this.springArticleRepository.findById(id.value())
      .<Either<Error, ArticleDTO>>map(jpa ->
        Either.right(this.mapper.toDTO(jpa)))
      .orElseGet(() -> Either.left(
        new Error.BusinessError.NotFound(
          ORIGIN, ENTITY, id.value())));
  }
 
  @Override
  public Either<Error, List<ArticleDTO>>
    findByAuthor(final AuthorId authorId) {
    final List<ArticleDTO> dtos = this.springArticleRepository
      .findByAuthorId(authorId.value()).stream()
      .map(this.mapper::toDTO)
      .toList();
    return Either.right(dtos);
  }
}

The port implementation maps before saving and translates a DataAccessException into a persistence error. section 9.5.1

Unit-test the adapter by mocking its data repository and checking mapping in both directions. Cover success, not-found for reads, and infrastructure failure; for writes, verify the delegated call and the error path. Choose the test double for the collaborator actually hidden by the adapter, rather than assuming every external adapter has the same test recipe. section 8.6.1 section 8.6

How Clean Applications with Hexagonal Architecture covers it

How deep it goes
Works through module boundaries, two-way mapping, runtime wiring, and adapter unit tests.
Examples
Uses an Article repository, a separate JPA entity, a mapper, and a mocked Spring Data repository.
What you can do after
Apply the pattern with Spring Data and JPA to implement a domain repository and test its translation and failure paths.
How it connects
Connects repository ports, domain aggregates, dependency injection, and hexagonal architecture.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clean Applications with Hexagonal Architecture. The section links point to the parts of the book it draws on.