Files
clean-architecture-backend-…/docs/jpa/entity-mapping-guide.md
T
DongHyeonka 1885bf8da7 fix!: 2차 재리뷰가 찾은 결함 29건을 고친다
문제: 재리뷰 수정 커밋(bbe944bd)만 다시 본 2차 재리뷰가 Important 7건,
Minor 22건을 찾았다. 결과 불명 503 뒤 같은 키를 다시 보내면 Redis
store가 lease 지난 실행을 넘겨받아 작업을 다시 돌렸다. replay TTL이
lease보다 짧으면 lease 도중 key가 사라져 같은 키가 두 번 실행됐다.
@SystemInvoked 규칙이 매뉴얼 09장의 이벤트 소비 경로까지 막았다. V22가
outbox_event에 가장 강한 잠금을 lock_timeout 없이 걸었다. prod의
fixture- 거부가 HOSTNAME 같은 비밀 아닌 값까지 막았다. 데모 허용 목록의
test·demo 프로필로 sample이 뜨지 않았다. 기동 rule bean의 @Value 필드가
조용히 null이 됐다.

방법: 영역별 4묶음이 test-driven-development 절차로 실패 테스트를
먼저 쓰고 고쳤다. 결정은 재리뷰 README 9.1절이다.
- 두 멱등성 store가 같은 계약을 따른다. lease가 지난 실행 기록은 다시
  돌리지 않고 포기로 표시해 500 RECOVERY_REQUIRED로 답한다. 기록 수명은
  lease + replay TTL이고, replay-ttl < processing-lease면 기동이 실패한다.
- 사용자 transport만 @SystemInvoked use case에 닿지 못한다. 메시지
  handler·scheduler는 새 표시 @SystemCaller(reason)를 달고 use case를
  생성자에서 new로 만든다. 매뉴얼 경로를 테스트로 고정했다.
- 아직 어디에도 적용되지 않은 마이그레이션(V20·V22·알림 V11~V13·sample
  V8_1·grpc V002·V003)에 lock_timeout 5s를 넣고, 텍스트 검사기와 실 PG
  lane을 더했다. 이미 배포된 24개는 동결 목록으로 둔다.
- fixture- 검사는 비밀로 분류된 값만 본다. sample은 local·test·demo에서
  object storage를 끈다. 기동 rule bean에 주입 멤버가 있으면 모든
  프로필에서 기동이 실패한다. 리뷰어가 제안한 "static @Bean 선언 강제"는
  문제없는 등록을 막고 @Value 필드는 통과시켜서 버렸다.
- 이 수정 전에 move된 파일의 쿼터 차이를 찾는 쿼리와 재계산 SQL을
  docs/fileserver/operations.md에 적었다.

위험·한계: lease 뒤 늦게 끝난 첫 시도의 결과는 기록되지 않는다(그 요청도
500). @SystemCaller가 없는 메시지 handler, 주입 멤버가 있는 기동 rule,
working-directory 없이 ./gradlew를 부르는 workflow 명령은 파생 서비스에서
새로 실패하거나 세지지 않는다(업그레이드 안내 B-14~16·B-36·B-39).
spotbugsTestFixtures는 게이트 밖이고 기준 커밋에서도 실패하며, 새 검사기의
정규식 경고 8건이 더해졌다. 실제 CI runner 실행은 확인하지 못했다(Gitea
repo의 Actions가 꺼져 있다).

검증: ci, 두 빌드의 verifyStrictLaneStages --dry-run, mainCheck,
:integrationCheck, -p optional-platforms ci integrationCheck
performanceCheck, :performanceCheck, :releaseCheck(-PgitRevision),
verify-compose-profile-contracts(18 lane) 첫 실행 통과. 쿼터 재계산
SQL은 실 PostgreSQL 16에서 차이 2행 → 0행을 확인했다.

Refs: docs/reviews/2026-11-03-rereview/README.md 9·9.1·10절
BREAKING CHANGE: replay-ttl < processing-lease 설정은 기동 실패, ledger
release가 claim token을 받는다, HttpBodyReadException(IOException 하위)이
본문 실패를 싣는다, 기동 rule·비밀 목록 bean의 주입 멤버 금지,
verifyStrictLaneStages가 workflow 명령의 working-directory로 빌드를 정한다.
2026-11-04 01:47:50 +09:00

7.7 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). 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) 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.