Files
clean-architecture-backend-…/docs/jpa/entity-mapping-guide.md
T
DongHyeonka ab5982e955 refactor(repo)!: 샘플 모듈과 그 참조를 지운다
문제: src/sample-portfolio(311파일)와 src/Dockerfile.sample이 빌드 8곳,
registry, PR job, spotbugs 제외, 매뉴얼·leaf 문서 수십 곳에 얽혀 있다.
매뉴얼과 생성 명령이 예시를 맡게 된 뒤로 샘플은 유지 비용만 남았고,
문서 일부는 이미 없는 태스크(sampleOffTest)와 ArchUnit 규칙을 가리킨다.

고른 방법: 소유자 결정(2026-11-07)대로 샘플을 폴더째 지우고 역할은
옮기지 않는다. 샘플을 가리키던 것도 같은 변경에서 지운다.
- 빌드: registry 행, 루트 build.gradle의 샘플 태스크·의존·단계
  (sampleWebContractCheck, :sample-portfolio:*, strict lane 단계),
  app-bootstrap architectureTestRuntimeOnly, spotbugs 제외 3곳
- CI: ci-quality-gates.yml의 sample-portfolio job과 release-gate 칸
- 테스트: SampleRuntimeDefaultsContractTest, Dockerfile.sample 비교 테스트,
  ArchUnit 규칙의 죽은 sample 패키지 제외. build-logic 테스트와
  application-core 테스트의 가짜 이름은 example-app으로 바꾼다
- 문서: 매뉴얼 예시를 실제 코드(durable operation, identifier,
  ErrorCodeRegistryMappingTest)로 바꾸고, 템플릿에 예가 없는 기법
  (유일 제약 → 같은 409)은 규칙과 확인 방법만 적는다. 결정 색인의
  샘플 전용 행은 "샘플과 함께 사라짐"으로 표시한다
버린 대안: 설계서 권장안(OpenAPI 스냅숏·웹 계약을 옮긴 뒤 삭제)은
소유자가 고르지 않았다.

위험·한계:
- 샘플 안에만 있던 검사(OpenAPI 스냅숏, Date 헤더, 가상 스레드 MDC
  전파, 요청당 SQL 수 단언)가 함께 사라진다. 소유자가 남기라 하면
  총괄이 따로 맡긴다.
- APP_CACHE_REDIS_ENABLED는 샘플이 읽지 않는 키라(설계서 가정과 다름)
  지우지 않고 src/README.md 문장만 고쳤다. 제거 기한 2026-11-30은 그대로.
- docs/capability-status.md 「제거된 코드」 표와 docs/work/evidence.md의
  샘플 경로는 이력이라 두었다.

검증(desktop, 트리 0525e14e, ~/t1-layout-logs/):
- ./gradlew :ci --warning-mode=fail rc=0 (502 executed, 83 from cache)
- :verifyStrictLaneStages --dry-run rc=0
- :app-bootstrap:documentContractTest rc=0
- -p build-logic check rc=0
- :verifyDependencyLocks rc=0
- python3 scripts/check-work-docs.py, 상대 링크 검사 rc=0

Refs: design-docs repo-structure/README.md 3.1, repo-structure/01-backend-layout.md 6.2
BREAKING CHANGE: src/sample-portfolio, src/Dockerfile.sample, 샘플 태스크와 job이 없어진다. 샘플을 고쳐 쓰던 파생 서비스는 병합 때 수정 대 삭제 충돌이 난다. docs/upgrade/2026-11-maturity-review.md B-49.
2026-11-07 12:21:03 +09:00

8.0 KiB

Entity Mapping Guide

Design §10-§13. The rules here exist because each one has a failure mode that is invisible in review and expensive in production.

The domain owns the model

The platform defines no business entity. Table names, column semantics, keys, unique and check requirements, associations, cascade rules, lock policy, and soft-delete policy all belong to the domain module. There is no GenericRepository<T, ID> and no platform base repository, because a single generic API forces every aggregate through the same operations — and one aggregate's later requirement then changes behaviour for all of them.

Entities must be proxyable

  • Not final. Hibernate creates a lazy proxy by generating a subclass; a final entity cannot be subclassed, so every association to it loads eagerly whatever the mapping says. Nothing errors.
  • A non-private no-arg constructor. The provider instantiates entities reflectively before populating fields.

EntityMappingCondition in the testkit enforces both.

Identifiers

Default to a sequence with an allocationSize that matches the migration's INCREMENT BY. When they disagree, the provider hands out identifiers the sequence has not reserved and the collision surfaces later as a primary-key violation under load.

GenerationType.IDENTITY is supported and limited: the key is assigned on insert, so the provider must execute each insert immediately to learn it, which disables JDBC insert batching entirely. HibernateBatchConfigurationGuard fails a batch profile that targets an IDENTITY entity rather than letting the import silently run an order of magnitude slower.

UUIDv7 (UuidV7Generator) is the application-side option. It is preferred over UUIDv4 for a primary key because v4 is uniformly random: every insert lands on a random leaf of the B-tree, so the index never stays in cache and write amplification grows with the table.

Values

  • Enums are EnumType.STRING or an explicit converter. Never ORDINAL — it stores the constant's position, so inserting a new constant anywhere but the end silently reinterprets every existing row.
  • Money is BigDecimal with explicit precision and scale. double cannot represent 0.1, so sums drift and reconciliation disagrees with the ledger.
  • Duration goes through a converter that stores milliseconds. The ISO-8601 text form sorts and compares wrongly in SQL.
  • Instant and OffsetDateTime map differently; a column typed for one cannot faithfully store the other.

Associations

Map each association from one side only. A JPA association between two entities is one foreign key column. A bidirectional pair (@ManyToOne on the child plus @OneToMany(mappedBy = ...) on the parent) stores that one column in two Java fields, and JPA writes only the owning one. The pair stays consistent only while every caller remembers to update both fields, and nothing fails when someone forgets.

What to use, in order of preference:

  1. An ID reference between aggregates. Hold the other aggregate's identifier as a plain column (UUID ownerId). This is what every production entity in the template does today. Loading the other aggregate is an explicit repository call, so a cross-aggregate load is visible in the code.
  2. A unidirectional @ManyToOne inside one aggregate, always fetch = FetchType.LAZY. JPA's default for a to-one association is EAGER, so every query that loads a child also queries for its parent — the most common accidental N+1 in a JPA application.
  3. A collection is a query, not a field. "The children of X" is a repository method (findByParentId, or a fetch-join or projection query that pages in SQL). The query states its own fetch plan and page, where a mapped collection hides both.
  4. Values the aggregate owns — a list of tags, a set of codes — are @ElementCollection (LAZY), not entities.

A unidirectional @OneToMany with its own @JoinColumn is the exception, not the default. Use it only for child entities the root genuinely owns and changes only through itself (the testkit's LifecycleParent and PagedParent are this shape). It still costs an UPDATE per child when the join column is nullable, and the collection still loads as a unit. The child then has no association back to the root — not even a read-only @ManyToOne on the same join column (insertable = false, updatable = false): that is the bidirectional pair again, without the mappedBy that names it. If the child needs the root, it holds the root's ID.

CascadeType.ALL with orphanRemoval is correct only for a child the aggregate genuinely owns. Between independent aggregates it deletes rows another part of the system still owns — another reason those are ID references.

JpaArchitectureRules.associationsAreMappedFromOneSideOnly() (testkit) fails the build on every bidirectional pair, on @Entity, @MappedSuperclass and @Embeddable types: an association that declares mappedBy (only that inverse half is reported), and two entities whose associations point at each other without mappedBy (both halves are reported — the @JoinColumn form above, review RR-03-04). The message says how the pair keeps the link: one join column mapped from both ends, or the link stored twice — a @OneToMany without @JoinColumn in a join table beside the child's own @ManyToOne column (what a forgotten mappedBy produces), or two @ManyToMany each owning a join table (re-review round 3, RR3-02-05). That last check also refuses two entities that each hold their own foreign key to the other (Order.@OneToOne latestInvoice with Invoice.@ManyToOne order). It is not one link mapped twice, and the message says so; it is refused on purpose, because the two tables then reference each other: neither row can be inserted or deleted first, one key has to be nullable and written by a second UPDATE, and the entity graph is a cycle. Keep the association on one side and give the other an ID or a query (re-review round 2, RR-02-15). A class that links to itself is a pair only when a second member points back the other way (@ManyToOne parent with @OneToMany children); two @ManyToOne links of a class to itself (a manager and a mentor) pass, because both keys point into the one table and there are no two tables to order. 이 규칙은 JpaProductionArchitectureTest(app-bootstrap architectureTest)가 운영 그래프 전체에 건다. The failure message names the fields and these alternatives.

Chosen and rejected:

Option Decision Why
One side only (ID reference, unidirectional @ManyToOne, collection by query), enforced by ArchUnit Chosen The link lives in one field, so there is nothing to keep in step. The rule turns a developer-memory convention into a build failure
Bidirectional with mappedBy and an addChild/removeChild helper that sets both sides Rejected The helper is the only thing keeping the two fields in step, and it must be remembered by every caller, every serializer (cycles in toString/JSON) and every cascade decision. A missed update leaves a row unlinked or a graph that disagrees with the database, with no error
Ban @OneToMany entirely Rejected for now It also bans a root-owned child collection, which has no second field to forget. Revisit if a real need for child entities that are read or changed on their own appears — that need is a sign they are a separate aggregate
Document only Rejected A convention the build does not check is invisible where the mapping is written, and the next copy of the template inherits whatever the examples show

Entities never leave the transaction

A controller must not return an entity, or a collection or Optional of one. Response serialisation happens after the transaction closes, so a lazy association touched by the serialiser either throws or — with OSIV on, which this platform forbids — issues a query from the view layer, one per element. EntityExposureCondition checks generic type arguments, not just the erased return type.