Files
clean-architecture-backend-…/docs/jpa/entity-mapping-guide.md
T
DongHyeonka bbe944bd3c fix!: 재리뷰가 찾은 결함과 색인에서 빠졌던 발견 5건을 고친다
문제: 성숙도 리뷰 수정을 다시 읽은 재리뷰(Critical 0, 회귀 0)가
Important 27건·Minor 41건을 찾았다. 수정이 새로 만든 결함이 많았다.
@SystemInvoked가 권한 규칙의 탈출구가 됐고, 데모 계정 거부가 정확히
prod일 때만 걸렸고, outbox 순서 번호가 업그레이드 때 뒤로 갔고,
GraphQL union 아래 복잡도가 0이었고, 서블릿 오류 응답이 success:true로
나갔고, 호출자 deadline이 breaker를 열었다. 원래 리뷰 색인이 06 영역
발견 5건(06-10~14)을 빠뜨려 그동안 처리되지 않았다.

방법: 영역별 7묶음이 test-driven-development 절차로 실패 테스트를
먼저 쓰고 고쳤다. 결정은 재리뷰 README 4절에 적었다: 순서 번호는 V21이
기록한 전역 floor부터, 데모 계정은 local·test·demo 허용 목록,
@SystemInvoked bean은 기동 실패, complete 단계 실패는
IDEMPOTENCY_COMPLETION_UNKNOWN(결과 불명), 캐시 조건부 쓰기는 별도
SCRIPT lane, strict lane 정책은 build cache 입력, 끝나지 않는 재시도
행은 원인 코드·지표·PARKED 절차. 레지스트리가 선언만 하고 아무 코드도
내보내지 않던 redis.capability.* 지표 6개는 빼고 runbook을 실제
지표(redis.lane.*) 기준으로 고쳤다.

위험·한계: V21을 V22 없이 직접 고쳤다(어느 배포에도 아직 없음). 이
브랜치의 V21을 적용한 개발 DB는 다시 만들어야 한다. 서블릿 오류
디스패치를 보안 체인이 허용한다. 발행·저장소 포트 시그니처가 바뀌어
파생 서비스 코드가 깨진다. prod에서 fixture-로 시작하는 설정값은
기동을 막는다. httpclient failure-injection lane의 main 단계 중복
실행은 이전 결정대로 남겼다. 실제 CI runner 실행은 확인하지 못했다.

검증: ci, mainCheck, :integrationCheck, -p optional-platforms ci
integrationCheck performanceCheck, :performanceCheck, :releaseCheck
(-PgitRevision), verify-compose-profile-contracts(18 lane) 통과.
첫 실행의 실패 2건(FindSecBugs 1, sample 동시 생성 테스트의 v4 event
id)은 고친 뒤 ci·integrationCheck·mainCheck를 다시 돌려 통과했다.

Refs: docs/reviews/2026-11-03-rereview/README.md 3·4·6·7절
BREAKING CHANGE: outbox 발행 포트와 저장소 포트 시그니처, 순서 번호
첫 값(V21 floor 다음), 샘플 데모 계정 프로필 허용 목록, 새 오류 코드
IDEMPOTENCY_COMPLETION_UNKNOWN, prod의 fixture- 값 거부, 기동 rule은
static·의존 없음이어야 한다.
2026-11-03 23:29:35 +09:00

7.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). A class that links to itself is a pair only when a second member points back the other way (@ManyToOne parent with @OneToMany children). JpaProductionArchitectureTest (app-bootstrap architectureTest) runs it over the production graph and SampleArchitectureTest over the sample. 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.