Paperless / rebuild
Course 2 28ef273

The persistence anti-corruption layer

Snapshot 28ef273Markdown

Assessment review: The lecture uses ACL for external/legacy semantic isolation. The repository uses the term more narrowly for persistence translation. See the distinction and remaining coupling.

The repository calls its persistence boundary an Anti-Corruption Layer (ACL). Its purpose is concrete: prevent JPA entities, lazy relationships, and persistence implementation details from becoming the business-layer model.

What the adapter protects

DocumentPersistence exposes domain-valued operations. JpaDocumentPersistence implements them using DocumentRepository, EntityManager, and DocumentEntityMapper. It maps Optional, Page, and List results before returning. A service should never need to know whether a returned document was managed by Hibernate.

In classic DDD, an ACL translates another system's language and semantics into the local model. Here that idea is applied to persistence. It overlaps with ports and adapters: the persistence interface is the port, the JPA class is the adapter, and mapping supplies translation. An interface without semantic translation is not sufficient evidence of a substantial ACL.

Walk through save

  1. The service supplies a Document with owner/team IDs and an optional domain document type.
  2. The adapter resolves JPA references through EntityManager.getReference.
  3. It passes those references to the pure entity mapper as References.
  4. The mapper constructs an entity retaining identity, timestamps, and version.
  5. The repository saves it; the adapter maps the returned entity back to the domain model.

Resolving a reference is persistence work. Deciding whether the actor may use that team is service policy. getReference is not a replacement for business validation and may defer database access.

Know the boundary's limits

The port uses Spring paging types and Java Optional, and the adapter's concurrency failures participate in Spring/JPA exception handling. It is isolated from entity representation, not from every framework concept. A stricter architecture could introduce its own paging and conflict types, at the cost of more translation.

PersistenceBoundaryTest scans source text for forbidden imports. It is a useful tripwire, not a complete proof of dependency direction: text checks can miss indirect dependencies, fully qualified references, and other rules such as services calling services.

Practice

Implement a small in-memory DocumentTypePersistence in a practice test. Reuse service tests with that implementation. Then describe which JPA behaviors the fake cannot establish: flush timing, version checks, database constraints, and lock behavior.

Draw a replacement storage adapter. Specify how it would implement refreshUnchanged before claiming the service can run unchanged against arbitrary storage.

Verification gate

Show that entity imports stop at the adapter/mapper boundary. Explain why entity mapping must occur while required lazy relationships are available. Distinguish a pure mapper from an adapter that performs I/O.

Read the implementation

Complete source walkthrough

Read these pinned files alongside the explanation above. These are the inspected implementation, not the capstone solution.

DocumentPersistence.kt

Browse source

package at.fhtw.swen3.paperless.document.persistence

import at.fhtw.swen3.paperless.document.model.Document
import java.util.Optional
import java.util.UUID
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable

interface DocumentPersistence {
    fun findById(id: UUID): Optional<Document>
    fun findOwnerOnlyDocuments(ownerId: UUID, documentTypeId: UUID?, pageable: Pageable): Page<Document>
    fun findVisibleDocuments(
        ownerId: UUID, teamIds: Set<UUID>, documentTypeId: UUID?, pageable: Pageable
    ): Page<Document>
    fun findOwnerOnlyDocuments(ownerId: UUID): List<Document>
    fun findVisibleDocuments(ownerId: UUID, teamIds: Set<UUID>): List<Document>
    fun save(document: Document): Document
    fun refreshUnchanged(document: Document): Document
    fun delete(document: Document)
    fun flush()
}

JpaDocumentPersistence.kt

Browse source

package at.fhtw.swen3.paperless.document.persistence

import at.fhtw.swen3.paperless.document.model.Document
import at.fhtw.swen3.paperless.document.entity.DocumentEntity
import at.fhtw.swen3.paperless.document.persistence.mapper.DocumentEntityMapper
import at.fhtw.swen3.paperless.document.persistence.repository.DocumentRepository
import at.fhtw.swen3.paperless.documenttype.entity.DocumentTypeEntity
import at.fhtw.swen3.paperless.team.entity.TeamEntity
import at.fhtw.swen3.paperless.user.entity.UserEntity
import jakarta.persistence.EntityManager
import jakarta.persistence.EntityNotFoundException
import jakarta.persistence.OptimisticLockException
import java.util.Optional
import java.util.UUID
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Repository

@Repository
class JpaDocumentPersistence(
    private val repository: DocumentRepository,
    private val entityManager: EntityManager,
    private val documentEntityMapper: DocumentEntityMapper
) : DocumentPersistence {

    override fun findById(id: UUID): Optional<Document> = repository.findById(id).map(documentEntityMapper::toModel)

    override fun findOwnerOnlyDocuments(ownerId: UUID, documentTypeId: UUID?, pageable: Pageable): Page<Document> =
        repository.findOwnerOnlyDocuments(ownerId, documentTypeId, pageable).map(documentEntityMapper::toModel)

    override fun findVisibleDocuments(
        ownerId: UUID, teamIds: Set<UUID>, documentTypeId: UUID?, pageable: Pageable
    ): Page<Document> = repository.findVisibleDocuments(ownerId, teamIds, documentTypeId, pageable)
        .map(documentEntityMapper::toModel)

    override fun findOwnerOnlyDocuments(ownerId: UUID): List<Document> =
        repository.findOwnerOnlyDocuments(ownerId).map(documentEntityMapper::toModel)

    override fun findVisibleDocuments(ownerId: UUID, teamIds: Set<UUID>): List<Document> =
        repository.findVisibleDocuments(ownerId, teamIds).map(documentEntityMapper::toModel)

    override fun save(document: Document): Document {
        val references = DocumentEntityMapper.References(
            owner = entityManager.getReference(UserEntity::class.java, document.ownerId),
            team = document.teamId?.let { entityManager.getReference(TeamEntity::class.java, it) },
            documentType = document.documentType?.let {
                entityManager.getReference(DocumentTypeEntity::class.java, requireNotNull(it.id))
            }
        )
        val entity = documentEntityMapper.toEntity(document, references)

        return documentEntityMapper.toModel(repository.save(entity))
    }

    override fun refreshUnchanged(document: Document): Document {
        val entity = repository.findById(requireNotNull(document.id)).orElseThrow {
            OptimisticLockException("Document was deleted concurrently")
        }
        try {
            entityManager.refresh(entity)
        } catch (exception: EntityNotFoundException) {
            throw OptimisticLockException("Document was deleted concurrently", exception)
        }
        val changed = entity.version != document.version || entity.team?.id != document.teamId ||
            entity.owner.id != document.ownerId
        if (changed) {
            throw OptimisticLockException("Document sharing changed concurrently")
        }

        return documentEntityMapper.toModel(entity)
    }

    override fun delete(document: Document) {
        repository.delete(entityManager.getReference(DocumentEntity::class.java, requireNotNull(document.id)))
    }

    override fun flush() = entityManager.flush()
}

DocumentEntityMapper.kt

Browse source

package at.fhtw.swen3.paperless.document.persistence.mapper

import at.fhtw.swen3.paperless.common.mapper.MappingConverters
import at.fhtw.swen3.paperless.document.entity.DocumentEntity
import at.fhtw.swen3.paperless.document.model.Document
import at.fhtw.swen3.paperless.documenttype.entity.DocumentTypeEntity
import at.fhtw.swen3.paperless.documenttype.persistence.mapper.DocumentTypeEntityMapper
import at.fhtw.swen3.paperless.team.entity.TeamEntity
import at.fhtw.swen3.paperless.user.entity.UserEntity
import org.mapstruct.InjectionStrategy
import org.mapstruct.Mapper
import org.mapstruct.Mapping
import org.mapstruct.MappingConstants
import org.mapstruct.ReportingPolicy

@Mapper(
    componentModel = MappingConstants.ComponentModel.SPRING,
    injectionStrategy = InjectionStrategy.CONSTRUCTOR,
    uses = [MappingConverters::class, DocumentTypeEntityMapper::class],
    unmappedTargetPolicy = ReportingPolicy.ERROR
)
interface DocumentEntityMapper {

    data class References(val owner: UserEntity, val team: TeamEntity?, val documentType: DocumentTypeEntity?)

    @Mapping(target = "id", source = "id", qualifiedByName = ["requireNotNull"])
    @Mapping(target = "ownerId", source = "owner.id", qualifiedByName = ["requireNotNull"])
    @Mapping(target = "teamId", source = "team.id")
    fun toModel(entity: DocumentEntity): Document

    fun toEntity(document: Document, references: References): DocumentEntity =
        DocumentEntity(
            id = document.id,
            title = document.title,
            originalFilename = document.originalFilename,
            contentType = document.contentType,
            fileSize = document.fileSize,
            owner = references.owner,
            team = references.team,
            status = document.status,
            ocrContent = document.ocrContent,
            summary = document.summary,
            storageKey = document.storageKey,
            documentType = references.documentType,
            createdAt = document.createdAt,
            updatedAt = document.updatedAt,
            version = document.version
        )
}

DocumentReferencesPersistence.kt

Browse source

package at.fhtw.swen3.paperless.document.persistence

import at.fhtw.swen3.paperless.documenttype.model.DocumentType
import at.fhtw.swen3.paperless.team.model.Team
import java.util.UUID

interface DocumentReferencesPersistence {
    fun ownerExists(id: UUID): Boolean
    fun findTeam(id: UUID): Team?
    fun findLockedTeam(id: UUID): Team?
    fun findDocumentType(id: UUID): DocumentType?
}

PersistenceBoundaryTest.kt

Browse source

package at.fhtw.swen3.paperless.architecture

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.nio.file.Files
import java.nio.file.Path

class PersistenceBoundaryTest {
    @Test
    fun business_layers_do_not_import_jpa_implementation_details_ok() {
        val sources = sourcesOutsidePersistence()

        assertThat(sources).isNotEmpty()
        assertThat(sources).allSatisfy { path ->
            assertThat(Files.readString(path)).describedAs(path.toString())
                .doesNotContain("import jakarta.persistence.", ".entity.", ".persistence.repository.")
                .doesNotContain(".persistence.mapper.", "import org.springframework.data.jpa.")
        }
    }

    @Test
    fun domain_persistence_interfaces_do_not_leak_jpa_types_ok() {
        val interfaces = persistenceInterfaces()

        assertThat(interfaces).isNotEmpty()
        assertThat(interfaces).allSatisfy { path ->
            assertThat(Files.readString(path)).describedAs(path.toString())
                .doesNotContain("jakarta.persistence.", ".entity.", ".persistence.repository.")
                .doesNotContain("JpaRepository", "EntityManager", ".persistence.mapper.")
        }
    }

    private fun sourcesOutsidePersistence(): List<Path> = Files.walk(Path.of("src/main/kotlin")).use { paths ->
        paths.filter { it.toString().endsWith(".kt") && !it.toString().contains("/persistence/") }
            .filter { path ->
                listOf("/service/", "/controller/", "/model/", "/mapper/").any { path.toString().contains(it) }
            }.toList()
    }

    private fun persistenceInterfaces(): List<Path> = Files.walk(Path.of("src/main/kotlin")).use { paths ->
        paths.filter { it.fileName.toString().endsWith("Persistence.kt") }
            .filter { !it.fileName.toString().startsWith("Jpa") }.toList()
    }
}
Ready to move on?

Complete the practice and verification gate first.

Search chapters, reference and source filenames.