Assessment review: The lectures prefer a rich, technology-independent domain. The current data models and service-heavy logic are a starting point to critique. See architecture corrections.
The code is a feature-organized layered application. document, documenttype, team, user, auth, and search each group related behavior. Inside a feature, controller, service, model, entity, and persistence packages make responsibilities visible.
Translate the domain language
A document has an uploader (ownerId), optional team sharing (teamId), classification (documentType), and a processing status. A team membership gives a user a role. Those names form a starting vocabulary for discussing rules with someone who does not care about table mappings.
| DDD concept | Evidence in this backend | What to avoid assuming |
|---|---|---|
| Entity identity | Document and Team use UUID identities | A Kotlin data class is automatically a value object |
| Value semantics | Immutable snapshots are copied on updates | Data-class equality expresses entity identity |
| Application service | DocumentServiceImpl coordinates access checks and persistence | Every service is a DDD domain service |
| Repository boundary | DocumentPersistence speaks in domain models | Spring Data repositories belong in business services |
| Aggregate consistency | Document updates preserve version and sharing state | Every JPA relationship belongs to one aggregate |
| Bounded context | Feature packages separate concepts | A package name proves an independent bounded context |
This is DDD-informed layering with substantial rules in application services. It is not a fully isolated domain core: service contracts use Spring Page and Resource, and persistence contracts use Pageable. Name these tradeoffs when describing the architecture.
Dependency direction
Controllers depend on service interfaces and DTO mappers. Services depend on domain-facing persistence interfaces. Adapters implement those interfaces and depend on entities, entity mappers, and Spring Data repositories. Domain models have no JPA annotations. Runtime calls move toward the database, while the business-facing interface defines what the adapter must provide.
The repository rule forbids services calling other services. Document operations consult team membership and reference persistence interfaces within the document service transaction. This keeps orchestration local, but it can duplicate rules across features. Do not present this team convention as a universal DDD requirement.
Practice
Design a new “archive document” use case on paper. Specify who may archive it, whether archived documents appear in search, and what happens to the stored file. Put each decision in the domain/application policy, HTTP contract, or persistence bucket. Decide whether an archive timestamp is sufficient or whether a lifecycle state needs explicit transition rules.
Compare a proposed rich Document.archive() model method with the existing service-based style. Explain how each would receive authorization context without reading global security state from the model.
Verification gate
Explain why mapping all entities to data classes alone does not implement DDD. State one invariant, its owner, and its transaction boundary. Explain why Document(id=x, title="A") and an updated snapshot with the same ID are conceptually the same entity even if structural equality differs.
Read the implementation
Complete source walkthrough
Read these pinned files alongside the explanation above. These are the inspected implementation, not the capstone solution.
layered-architecture.md
# Layered Architecture
Each feature exposes a service interface and isolates JPA behind an Anti-Corruption Layer:
```
at/fhtw/swen3/paperless/<feature>/
controller/ <Feature>Controller
service/ <Feature>Service, <Feature>ServiceImpl
model/ immutable domain models and enums
dto/ request and response types
mapper/ <Feature>Mapper — DTO ↔ model
entity/ JPA entities
persistence/ <Feature>Persistence — domain-facing interface
Jpa<Feature>Persistence — Spring @Repository adapter
repository/ plain Spring Data interfaces
mapper/ <Feature>EntityMapper — pure model ↔ entity mapping
```
`model/`, `entity/`, `service/`, and `persistence/` are sibling folders within each
feature. Entities stay separate from the persistence adapters and repositories.
## Layer contract
| Layer | May depend on | Must not depend on |
| --- | --- | --- |
| Controller / DTO mapper | Service interfaces, models, DTOs | Persistence interfaces or implementation details |
| Service | Domain persistence interfaces, models, paging types | Other services, JPA, entities, Spring Data repositories, entity mappers, DTOs |
| Persistence interface | Domain models, UUIDs, Optional, Page / Pageable | JPA, entities, Spring Data repositories, services, DTOs |
| JPA adapter | Entities, repositories, entity mappers, EntityManager | Controllers, DTOs, business services |
| Entity mapper | Models and entities | I/O, repositories, services, business rules |
| Domain model | Kotlin / Java value types | JPA and Spring framework classes |
## Request flow
```
Controller → DTO mapper → Service → Persistence interface
↓
JPA adapter → entity mapper → Spring Data repository
```
Adapters translate all persistence results to domain models before returning, including
optional values, lists, pages, and lazy relationships. Services never receive managed
entities and update immutable domain values with `copy`.
Business validation, authorization, and domain not-found errors remain in services.
Adapters resolve entity references and handle database operations, mapping, flushes,
and concurrent-deletion / stale-version detection. They do not decide who may access data.
Spring Data repositories stay plain interfaces; no handwritten repository implementations.
Services own transactions. Adapter calls participate in those transactions so lazy
relationships are materialized while the persistence context is open. Existing
pessimistic locks for user authentication and team membership changes are preserved.
The document adapter carries the domain version through mapping and compares it,
owner ID, and team ID after refresh before update or deletion. Service file cleanup
continues to depend on transaction completion and explicit flush failures.
Services never inject or call other services, including services from the same feature.
Cross-feature operations use domain-facing persistence interfaces within the calling
service's transaction (for example account deletion checking team memberships and
revoking tokens). JPA types are confined to
entity and persistence packages, even when associations refer to another feature's entities.
`DocumentReferencesPersistence` provides domain-valued reference lookups and team
locks to document services. Authentication owns credential validation, user locking, and token replacement.
Search owns its membership-filtered candidate lookup. `AccessToken` carries a digest,
user ID, and expiry, without leaking a user entity. New documents have a nullable ID until persisted; response mapping requires an ID.
See [Annotations](annotations.md), [Mappers](mappers.md), and [Testing](testing.md).
## Shared entity properties
UUID entities inherit `id`, `createdAt`, `updatedAt`, and `version` from
`common/entity/AbstractEntity`, a JPA mapped superclass. Hibernate generates UUIDs,
maintains creation/update timestamps, and checks the inherited version on writes.
Domain models and entity mappers carry the loaded version through updates to preserve
optimistic locking. Membership updates mutate the managed entity and retain its version.
Flyway V2 adds and backfills the new columns for existing databases.
`AccessTokenEntity` keeps its digest primary key and expiration lifecycle; it does not
inherit a generated UUID identity.
Document.kt
package at.fhtw.swen3.paperless.document.model
import at.fhtw.swen3.paperless.documenttype.model.DocumentType
import java.time.Instant
import java.util.UUID
data class Document(
val id: UUID?,
val title: String,
val originalFilename: String,
val contentType: String,
val fileSize: Long,
val status: ProcessingStatus,
val ocrContent: String?,
val summary: String?,
val storageKey: String?,
val documentType: DocumentType?,
val createdAt: Instant,
val updatedAt: Instant,
val ownerId: UUID,
val teamId: UUID? = null,
val version: Long = 0
)
Team.kt
package at.fhtw.swen3.paperless.team.model
import java.time.Instant
import java.util.UUID
data class Team(
val id: UUID?,
val name: String,
val description: String?,
val createdAt: Instant,
val updatedAt: Instant?,
val ownerId: UUID? = null,
val version: Long = 0
)
TeamMember.kt
package at.fhtw.swen3.paperless.team.model
import at.fhtw.swen3.paperless.user.model.User
import java.time.Instant
data class TeamMember(
val team: Team,
val user: User,
val role: Role,
val joinedAt: Instant?
)
DocumentService.kt
package at.fhtw.swen3.paperless.document.service
import at.fhtw.swen3.paperless.document.model.Document
import at.fhtw.swen3.paperless.document.model.DocumentUpdate
import at.fhtw.swen3.paperless.document.model.DocumentUpload
import java.util.UUID
import org.springframework.core.io.Resource
import org.springframework.data.domain.Page
interface DocumentService {
fun searchDocuments(
page: Int,
size: Int,
sort: String,
documentTypeId: UUID?
): Page<Document>
fun getDocument(id: UUID): Document
fun uploadDocument(upload: DocumentUpload): Document
fun updateDocument(id: UUID, update: DocumentUpdate): Document
fun deleteDocument(id: UUID)
fun downloadDocument(id: UUID): Resource
}