Clean Architecture requires the domain layer to remain pure and decoupled from any technical dependencies. However, JPA and Hibernate introduce annotations and constraints that, if applied directly to domain entities, pollute business logic. Flyway adds another layer: versioned management of the database schema. This article documents how to integrate JPA, Hibernate, and Flyway into the infrastructure layer of a Clean Architecture Spring Boot 3.4 application, maintaining strict separation between domain entities and JPA entities, implementing the mapper pattern, creating idempotent repository adapters, and tracking schema versioning with semantic migrations.
Introduction: The Problem of JPA Coupling in Domain
When you start a Spring Boot project, the temptation is great: you'll define the domain entity directly with JPA's @Entity and @Column. The code is minimal, immediate, tested with a 20-second "unit test" (that starts the entire Spring context). What's the price?
Six months later, you discover that:
- You can't test business logic without Spring; each test takes 500ms instead of 1ms.
- If you decide to change databases (PostgreSQL → MongoDB), you must rewrite all entities.
- Business logic is fragmented: part in the entity (getters/setters), part in services, part in SQL triggers.
- A colleague accidentally adds a business rule in the REST controller.
Clean Architecture solves this by creating two separate models:
- Domain Entity: Pure Java record or class, zero Spring annotations, encapsulated business logic, immutable.
- JPA Entity: Mutable class in infrastructure layer, with @Entity and @Column, gateway to Hibernate and the database.
A mapper converts between the two. Flyway tracks schema changes. The repository adapter implements the domain port interface. Result: pure domain, isolated technical infrastructure, lasting testability and maintainability.
Problem 1: Pure Domain Entity vs JPA Entity
Anti-Pattern: Entity Coupled to JPA
// ANTI-PATTERN: Business logic + Spring annotations mixed together
@Entity
@Table(name = "articles")
public class Article {
@Id @GeneratedValue(strategy = GenerationType.UUID)
private UUID id;
@Column(nullable = false, length = 255)
private String title;
@Column(columnDefinition = "TEXT")
private String content;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id", nullable = false)
private Author author;
@Transient // Not persisted
private int viewCount;
// No business logic, just getters/setters
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
// Test: 500ms (Spring context needed)
}
Pattern: Pure Domain Entity in Domain Layer
// Layer 1: Domain - Pure entity, zero Spring
public record Article(
ArticleId id,
Title title,
Content content,
AuthorId authorId,
ZonedDateTime createdAt,
PublicationStatus status
) {
// Encapsulated business logic
public void publish() {
if (!status.equals(PublicationStatus.DRAFT)) {
throw new ArticleAlreadyPublishedException("Article already published");
}
// Mark as published (return new Article(...))
}
public int estimatedReadTime() {
int wordCount = content.value().split("\\s+").length;
return Math.max(1, wordCount / 200); // 200 words/min
}
public boolean canBeEditedBy(AuthorId editor) {
return this.authorId.equals(editor) || status.equals(PublicationStatus.DRAFT);
}
// Factory method
public static Article create(Title title, Content content, AuthorId authorId) {
return new Article(
ArticleId.generate(),
title,
content,
authorId,
ZonedDateTime.now(ZoneId.of("UTC")),
PublicationStatus.DRAFT
);
}
}
// Immutable Value Objects
public record Title(String value) {
public Title {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Title cannot be empty");
}
if (value.length() > 255) {
throw new IllegalArgumentException("Title too long");
}
}
}
public record Content(String value) {
public Content {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("Content cannot be empty");
}
}
}
public record ArticleId(UUID value) {
public ArticleId {
Objects.requireNonNull(value);
}
public static ArticleId generate() {
return new ArticleId(UUID.randomUUID());
}
}
// Immutable enum
public enum PublicationStatus {
DRAFT, PUBLISHED, ARCHIVED
}
Pattern: Separate JPA Entity in Infrastructure
// Layer 3: Infrastructure - JPA Entity (persistence only)
@Entity
@Table(name = "articles")
public class ArticleJpaEntity {
@Id
private String id; // UUID as String
@Column(nullable = false, length = 255)
private String title;
@Column(columnDefinition = "TEXT", nullable = false)
private String content;
@Column(name = "author_id", nullable = false)
private String authorId;
@Column(name = "created_at", nullable = false, updatable = false)
@CreationTimestamp
private ZonedDateTime createdAt;
@Column(name = "status", nullable = false)
@Enumerated(EnumType.STRING)
private String status;
// No business logic, just getters/setters for Hibernate
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
// ... setters for all fields
}
Tradeoff: Pure Domain vs JPA Coupled
| Aspect | Pure Domain (Pattern) | JPA Coupled (Anti-Pattern) |
|---|---|---|
| Testability | 1ms per test (no Spring) | 500ms per test (Spring context) |
| Business Logic | Encapsulated in entity | Scattered: entity, service, controller |
| Reusability | Zero dependencies, reusable everywhere | Depends on Hibernate, not reusable |
| DB Evolution | Adaptable to MongoDB, NoSQL, files | Locked to JPA and SQL |
| Initial Complexity | +20% (mapper, adapter) | Minimal (direct JPA) |
Solution: Mapper Pattern for Data Conversion
What the Mapper Does
The mapper performs bidirectional conversion between domain entity and JPA entity. It lives in the infrastructure layer and is responsible for:
- JPA Entity → Domain Entity: load data from DB, convert to pure domain objects.
- Domain Entity → JPA Entity: take domain entity, convert to persistable form.
Pattern: Explicit Manual Mapper
// Layer 3: Infrastructure - Mapper
@Component
public class ArticleMapper {
// From JPA Entity to Domain Entity
public Article toDomain(ArticleJpaEntity jpaEntity) {
return new Article(
new ArticleId(UUID.fromString(jpaEntity.getId())),
new Title(jpaEntity.getTitle()),
new Content(jpaEntity.getContent()),
new AuthorId(UUID.fromString(jpaEntity.getAuthorId())),
jpaEntity.getCreatedAt(),
PublicationStatus.valueOf(jpaEntity.getStatus())
);
}
// From Domain Entity to JPA Entity
public ArticleJpaEntity toJpa(Article domain) {
ArticleJpaEntity jpa = new ArticleJpaEntity();
jpa.setId(domain.id().value().toString());
jpa.setTitle(domain.title().value());
jpa.setContent(domain.content().value());
jpa.setAuthorId(domain.authorId().value().toString());
jpa.setCreatedAt(domain.createdAt());
jpa.setStatus(domain.status().name());
return jpa;
}
}
Pattern: MapStruct Mapper (Generated)
// Dependencies in pom.xml:
// <dependency>
// <groupId>org.mapstruct</groupId>
// <artifactId>mapstruct</artifactId>
// <version>1.5.5.Final</version>
// </dependency>
@Mapper(componentModel = "spring")
public interface ArticleMapperGenerated {
@Mapping(source = "id", target = "id")
@Mapping(source = "title", target = "title")
@Mapping(source = "content", target = "content")
Article toDomain(ArticleJpaEntity jpaEntity);
@Mapping(source = "id", target = "id")
ArticleJpaEntity toJpa(Article domain);
}
Solution: Repository Adapter to Abstract JPA
Port: Repository Interface in Domain
// Layer 1: Domain - Port (interface, zero Spring)
public interface ArticleRepository {
Optional<Article> findById(ArticleId id);
List<Article> findByAuthorId(AuthorId authorId);
Article save(Article article);
void delete(ArticleId id);
}
Adapter: Repository Implementation in Infrastructure
// Layer 3: Infrastructure - Adapter
@Repository
public class ArticleJpaAdapter implements ArticleRepository {
private final ArticleJpaRepository jpaRepository; // Spring Data
private final ArticleMapper mapper;
public ArticleJpaAdapter(
ArticleJpaRepository jpaRepository,
ArticleMapper mapper
) {
this.jpaRepository = jpaRepository;
this.mapper = mapper;
}
@Override
public Optional<Article> findById(ArticleId id) {
return jpaRepository.findById(id.value().toString())
.map(mapper::toDomain);
}
@Override
public List<Article> findByAuthorId(AuthorId authorId) {
return jpaRepository.findByAuthorId(authorId.value().toString())
.stream()
.map(mapper::toDomain)
.toList();
}
@Override
public Article save(Article article) {
ArticleJpaEntity jpaEntity = mapper.toJpa(article);
ArticleJpaEntity saved = jpaRepository.save(jpaEntity);
return mapper.toDomain(saved);
}
@Override
public void delete(ArticleId id) {
jpaRepository.deleteById(id.value().toString());
}
}
// Layer 3: Spring Data convenience interface (private)
@Repository
interface ArticleJpaRepository extends JpaRepository<ArticleJpaEntity, String> {
List<ArticleJpaEntity> findByAuthorId(String authorId);
}
Use Case: Repository Adapter Transparent to Use Case
// Layer 2: Application - Use case uses port, doesn't know JPA
@Service
@Transactional
public class PublishArticleUseCase {
private final ArticleRepository articleRepository; // Port (interface)
public PublishArticleUseCase(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
public void execute(PublishArticleCommand command) {
// 1. Load from DB
Article article = articleRepository.findById(command.articleId())
.orElseThrow(() -> new ArticleNotFoundException("Not found"));
// 2. Apply business logic (domain layer)
article.publish();
// 3. Save (adapter maps back to JPA)
articleRepository.save(article);
}
}
Solution: Flyway for Idempotent Schema Versioning
What Flyway Does
Flyway is a database migration tool that tracks database schema changes in versioned, idempotent, and reversible form. Each migration is a SQL file with a version number (V001, V002, V003).
Setup: Spring Boot Integration
<!-- pom.xml -->
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>10.10.0</version>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-database-postgresql</artifactId>
<version>10.10.0</version>
</dependency>
# application.yml
spring:
datasource:
url: jdbc:postgresql://localhost:5432/portfolio
username: postgres
password: secret
jpa:
hibernate:
ddl-auto: validate # Flyway manages schema, Hibernate validates it
flyway:
locations: classpath:db/migration
schemas: public
baselineOnMigrate: true # For existing DB, create baseline
validateOnMigrate: true # Fail fast if migration is broken
Structure: Migration File Organization
src/main/resources/db/migration/
├── V001__create_articles_table.sql
├── V002__add_author_foreign_key.sql
├── V003__create_article_comments_table.sql
├── V004__add_publication_status_column.sql
├── V005__create_articles_index_author_id.sql
└── R__refresh_materialized_view.sql # Repeatable, run on every deploy
Example: First Migration
-- src/main/resources/db/migration/V001__create_articles_table.sql
CREATE TABLE IF NOT EXISTS articles (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
author_id UUID NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(50) NOT NULL DEFAULT 'DRAFT',
CONSTRAINT articles_author_id_fk
FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE RESTRICT
);
CREATE INDEX idx_articles_author_id ON articles(author_id);
CREATE INDEX idx_articles_status ON articles(status);
Example: Schema Evolution
-- src/main/resources/db/migration/V002__add_view_count_column.sql
ALTER TABLE articles ADD COLUMN IF NOT EXISTS view_count INTEGER DEFAULT 0;
ALTER TABLE articles ADD COLUMN IF NOT EXISTS published_at TIMESTAMP WITH TIME ZONE;
-- Historical data: all PUBLISHED articles get published_at = created_at
UPDATE articles SET published_at = created_at WHERE status = 'PUBLISHED';
-- src/main/resources/db/migration/V003__create_article_comments_table.sql
CREATE TABLE IF NOT EXISTS article_comments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
article_id UUID NOT NULL,
author_id UUID NOT NULL,
body TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT article_comments_article_id_fk
FOREIGN KEY (article_id) REFERENCES articles(id) ON DELETE CASCADE,
CONSTRAINT article_comments_author_id_fk
FOREIGN KEY (author_id) REFERENCES users(id) ON DELETE RESTRICT
);
CREATE INDEX idx_article_comments_article_id ON article_comments(article_id);
Pattern: Idempotency and Migration Rollback
Rules for Robust Migrations
- Use IF NOT EXISTS / IF EXISTS: Migrations must be re-executable without errors (for tests, rollback, recovery).
- Historical data with UPDATE: If you add a NOT NULL column, populate historical data before adding the constraint.
- Never use ALTER TABLE DROP carelessly: Could delete production data.
- Document semantic changes: Add comments in the SQL file explaining why the change occurs.
Example: Failed Migration and Recovery
-- V004__add_unique_email_constraint.sql (WRONG - will fail if duplicate emails)
ALTER TABLE articles ADD CONSTRAINT uk_articles_slug UNIQUE (slug);
-- PROBLEM: If articles have duplicate slugs, ALTER TABLE fails.
-- FIX: Correct version in V005__cleanup_duplicate_slugs.sql
-- V005__cleanup_duplicate_slugs.sql
-- 1. Identify duplicates
WITH duplicates AS (
SELECT slug, COUNT(*) as cnt FROM articles GROUP BY slug HAVING cnt > 1
)
-- 2. Assign unique slug to duplicates
UPDATE articles a SET slug = slug || '-' || id WHERE slug IN (SELECT slug FROM duplicates);
-- 3. Now add constraint
ALTER TABLE articles ADD CONSTRAINT uk_articles_slug UNIQUE (slug);
Complete Integration: End-to-End Use Case
Scenario: Create and Save an Article
// Layer 2: Application - Use Case
@Service
@Transactional
public class CreateArticleUseCase {
private final ArticleRepository articleRepository;
public CreateArticleUseCase(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
public CreateArticleResponse execute(CreateArticleRequest request) {
// 1. Domain layer: create pure entity
Article article = Article.create(
new Title(request.title()),
new Content(request.content()),
new AuthorId(UUID.fromString(request.authorId()))
);
// 2. Infrastructure layer (adapter): save
Article saved = articleRepository.save(article);
// 3. Return response
return CreateArticleResponse.fromDomain(saved);
}
}
// Layer 3: Infrastructure - The save happens like this:
// 1. CreateArticleUseCase calls articleRepository.save(Article)
// 2. ArticleJpaAdapter.save() receives domain entity
// 3. Mapper converts Article → ArticleJpaEntity
// 4. JpaRepository.save() persists to PostgreSQL via Flyway schema
// 5. Hibernate loads the saved record (with generated ID)
// 6. Mapper converts ArticleJpaEntity → Article (domain)
// 7. Use case returns saved domain entity
Best Practices and Consolidated Patterns
Implementation Checklist
- Domain entities are immutable (Java records or @Immutable class).
- Domain layer has zero Spring annotations.
- JPA entities separated in infrastructure, mutable.
- Mapper performs bidirectional conversion.
- Repository adapter implements domain port interface.
- Flyway tracks every schema change in versioned SQL file.
- Migration files are idempotent with IF NOT EXISTS.
- @Transactional only in application layer (use case).
- Complex queries in Query Objects or Spring Data @Query.
- Test domain entities without Spring (1ms), adapter tests with @DataJpaTest.
Conclusion
Integrating JPA and Flyway in Clean Architecture requires initial discipline, but pays off durably: the domain layer remains pure, testable, and independent of persistence technology. Separation between domain entity and JPA entity makes code resilient to changing requirements. Flyway tracks schema evolution in versioned and reversible form. The repository adapter isolates Spring Data usage to the infrastructure layer. Result: a maintainable codebase for 5+ years, with fast tests, safe refactoring, and clear, localized business logic.

Commenti
Caricamento commenti...
Sign in to comment